• Stars
    star
    146
  • Rank 252,769 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 10 years ago
  • Updated about 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Reactive Data Source for Search

search-source

Reactive Data Source for building search solutions with Meteor

If you are new to search source, it's a good idea to look at this introductory article on MeteorHacks.

Installation

meteor add meteorhacks:search-source

Creating a source in client

var options = {
  keepHistory: 1000 * 60 * 5,
  localSearch: true
};
var fields = ['packageName', 'description'];

PackageSearch = new SearchSource('packages', fields, options);
  • First parameter for the source is the name of the source itself. You need to use it for defining the data source on the server.
  • second arguments is the number of fields to search on the client (used for client side search and text transformation)
  • set of options. Here are they
    • keepHistory - cache the search data locally. You need to give an expire time(in millis) to cache it on the client. Caching is done based on the search term. Then if you search again for that term, it search source won't ask the server to get data again.
    • localSearch - allow to search locally with the data it has.

Define the data source on the server

In the server, get data from any backend and send those data to the client as shown below. You need to return an array of documents where each of those object consists of _id field.

Just like inside a method, you can use Meteor.userId() and Meteor.user() inside a source definition.

SearchSource.defineSource('packages', function(searchText, options) {
  var options = {sort: {isoScore: -1}, limit: 20};

  if(searchText) {
    var regExp = buildRegExp(searchText);
    var selector = {packageName: regExp, description: regExp};
    return Packages.find(selector, options).fetch();
  } else {
    return Packages.find({}, options).fetch();
  }
});

function buildRegExp(searchText) {
  var words = searchText.trim().split(/[ \-\:]+/);
  var exps = _.map(words, function(word) {
    return "(?=.*" + word + ")";
  });
  var fullExp = exps.join('') + ".+";
  return new RegExp(fullExp, "i");
}

Get the reactive data source

You can get the reactive data source with the PackageSearch.getData api. This is an example usage of that:

Template.searchResult.helpers({
  getPackages: function() {
    return PackageSearch.getData({
      transform: function(matchText, regExp) {
        return matchText.replace(regExp, "<b>$&</b>")
      },
      sort: {isoScore: -1}
    });
  }
});

.getData() api accepts an object with options (and an optional argument to ask for a cursor instead of a fetched array; see example below). These are the options you can pass:

  • transform - a transform function to alter the selected search texts. See above for an example usage.
  • sort - an object with MongoDB sort specifiers
  • limit - no of objects to limit
  • docTransform - a transform function to transform the documents in the search result. Use this for computed values or model helpers. (see example below)
Template.searchResult.helpers({
  getPackages: function() {
    return PackageSearch.getData({
      docTransform: function(doc) {
        return _.extend(doc, {
          owner: function() {
            return Meteor.users.find({_id: this.ownerId})
          }
        })
      },
      sort: {isoScore: -1}
    }, true);
  }
});

Searching

Finally we can invoke search queries by invoking following API.

PackageSearch.search("the text to search");

Status

You can get the status of the search source by invoking following API. It's reactive too.

var status = PackageSearch.getStatus();

Status has following fields depending on the status.

  • loading - indicator when loading
  • loaded - indicator after loaded
  • error - the error object, mostly if backend data source throws an error

Metadata

With metadata, you get some useful information about search along with the search results. These metadata can be time it takes to process the search or the number of results for this search term.

You can get the metadata with following API. It's reactive too.

var metadata = PackageSearch.getMetadata();

Now we need a way to send metadata to the client. This is how we can do it. You need to change the server side search source as follows

SearchSource.defineSource('packages', function(searchText, options) {
  var data = getSearchResult(searchText);
  var metadata = getMetadata();

  return {
    data: data,
    metadata: metadata
  }
});

Passing Options with Search

We can also pass some options while searching. This is the way we can implement pagination and other extra functionality.

Let's pass some options to the server:

// In the client
var options = {page: 10};
PackageSearch.search("the text to search", options);

Now you can get the options object from the server. See:

// In the server
SearchSource.defineSource('packages', function(searchText, options) {
  // do anything with options
  console.log(options); // {"page": 10}
});

Get Current Search Query

You can get the current search query with following API. It's reactive too.

var searchText = PackageSearch.getCurrentQuery();

Clean History

You can clear the stored history (if enabled the keepHistory option) via the following API.

PackageSearch.cleanHistory();

Defining Data Source in the Client

Sometime, we don't need to fetch data from the server. We need to get it from a data source aleady available on the client. So, this is how we do it:

PackageSearch.fetchData = function(searchText, options, success) {
  SomeOtherDDPConnection.call('getPackages', searchText, options, function(err, data) {
    success(err, data);
  });
};

More Repositories

1

cluster

Clustering solution for Meteor with load balancing and service discovery
JavaScript
631
star
2

npm

Complete NPM integration for Meteor
JavaScript
508
star
3

meteord

MeteorD - Docker Runtime for Meteor Apps for Production Deployments
Shell
439
star
4

meteor-ssr

Server Side Rendering for Meteor
JavaScript
264
star
5

sikka

Sikka - A Firewall for Meteor Apps
JavaScript
258
star
6

kadira

Performance Monitoring for Meteor
JavaScript
217
star
7

meteor-aggregate

Proper MongoDB aggregations support for Meteor
JavaScript
189
star
8

picker

Server Side Router for Meteor
JavaScript
182
star
9

meteor-down

Load testing for Meteor
JavaScript
175
star
10

flow-components

Build your Meteor app with Components.
JavaScript
132
star
11

unblock

this.unblock inside publications :D
JavaScript
87
star
12

meteor-inject-initial

Allow injection of arbitrary data to initial Meteor HTML page
JavaScript
80
star
13

meteor-async

Set of async utilities to work with NPM modules inside Meteor
JavaScript
63
star
14

goddp

DDP Server implemented with golang
Go
47
star
15

meteorx

Exposing some of the internal Meteor API prototypes
JavaScript
41
star
16

mup-frontend-server

Frontend Server for Meteor Up
Nginx
37
star
17

kube-init

Easiest way to deploy a Kubernetes Cluster to learn Kubernetes
Shell
34
star
18

zones

Zone.js integration for meteor
JavaScript
30
star
19

meteorhacks.github.io

MeteorHacks Website
HTML
29
star
20

hyperkube

Hyperkube
Shell
20
star
21

inject-data

A way to inject data to the client with initial HTML
JavaScript
18
star
22

kadira-profiler

CPU Profiling support for Kadira
JavaScript
14
star
23

bddp

DDP like binary protocol implemented using cap'n proto
Go
12
star
24

repeeet

making repeeet tweeting super simple
JavaScript
11
star
25

code-standards

Code Standards for MeteorHacks projects
9
star
26

js-pipes

MongoDB aggregation pipeline implementation in JavaScript
JavaScript
9
star
27

meteor-customer-io

Customer.io Integration for Meteor
JavaScript
9
star
28

cluster-performance

Performance Test for Cluster
JavaScript
8
star
29

docker-librato

Forward all stats from all running docker containers to Librato
JavaScript
8
star
30

kdb

ACID High Performance Time Series DB for any kind of storage - No it isn't
Go
7
star
31

meteor-todo-app

Simple Todo App with Meteor
JavaScript
5
star
32

gocluster

Meteor Cluster protocol implemented for Go
Go
4
star
33

meteor-collection-utils

Expose some underline collection apis
JavaScript
4
star
34

find-faster-chat-demo

Simple Chat To Demo Meteor Fast Finder Use
JavaScript
3
star
35

ddptest

Test DDP servers
JavaScript
3
star
36

zones-simple-example

Simple Example Meteor App with Zones
JavaScript
2
star
37

mongo-search

Simple API to use MongoDB Full Text search with Meteor
2
star
38

kmdb

metric database powered by kdb
Go
2
star
39

meteor-down-backdoor

Backdoor Meteor package for MeteorDown
JavaScript
2
star
40

kadira-binary-deps

Binary Dependencies for Kadira
JavaScript
2
star
41

simple-rpc-go

A really simple and fast binary RPC middleware
Go
2
star
42

kmdb-node

NodeJS client for kmdb
JavaScript
2
star
43

nsqd-to-librato

Send NSQ stats to librato
JavaScript
2
star
44

lean-components-example

lean-components-example
JavaScript
2
star
45

meteor-zone-example

Example meteor app for meteor-zone package
JavaScript
1
star
46

node-histo-utils

A set of utilities to create, merge and manage histograms
JavaScript
1
star
47

blaze-ext

Create blaze templates with .blaze extension
1
star