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
1var options = { 2 keepHistory: 1000 * 60 * 5, 3 localSearch: true 4}; 5var fields = ['packageName', 'description']; 6 7PackageSearch = 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()
andMeteor.user()
inside a source definition.
1SearchSource.defineSource('packages', function(searchText, options) { 2 var options = {sort: {isoScore: -1}, limit: 20}; 3 4 if(searchText) { 5 var regExp = buildRegExp(searchText); 6 var selector = {packageName: regExp, description: regExp}; 7 return Packages.find(selector, options).fetch(); 8 } else { 9 return Packages.find({}, options).fetch(); 10 } 11}); 12 13function buildRegExp(searchText) { 14 var words = searchText.trim().split(/[ \-\:]+/); 15 var exps = _.map(words, function(word) { 16 return "(?=.*" + word + ")"; 17 }); 18 var fullExp = exps.join('') + ".+"; 19 return new RegExp(fullExp, "i"); 20}
Get the reactive data source
You can get the reactive data source with the PackageSearch.getData
api. This is an example usage of that:
1Template.searchResult.helpers({ 2 getPackages: function() { 3 return PackageSearch.getData({ 4 transform: function(matchText, regExp) { 5 return matchText.replace(regExp, "<b>$&</b>") 6 }, 7 sort: {isoScore: -1} 8 }); 9 } 10});
.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 specifierslimit
- no of objects to limitdocTransform
- a transform function to transform the documents in the search result. Use this for computed values or model helpers. (see example below)
1Template.searchResult.helpers({ 2 getPackages: function() { 3 return PackageSearch.getData({ 4 docTransform: function(doc) { 5 return _.extend(doc, { 6 owner: function() { 7 return Meteor.users.find({_id: this.ownerId}) 8 } 9 }) 10 }, 11 sort: {isoScore: -1} 12 }, true); 13 } 14});
Searching
Finally we can invoke search queries by invoking following API.
1PackageSearch.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.
1var 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
1SearchSource.defineSource('packages', function(searchText, options) { 2 var data = getSearchResult(searchText); 3 var metadata = getMetadata(); 4 5 return { 6 data: data, 7 metadata: metadata 8 } 9});
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:
1// In the client 2var options = {page: 10}; 3PackageSearch.search("the text to search", options);
Now you can get the options object from the server. See:
1// In the server 2SearchSource.defineSource('packages', function(searchText, options) { 3 // do anything with options 4 console.log(options); // {"page": 10} 5});
Get Current Search Query
You can get the current search query with following API. It's reactive too.
1var searchText = PackageSearch.getCurrentQuery();
Clean History
You can clear the stored history (if enabled the keepHistory
option) via the following API.
1PackageSearch.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:
1PackageSearch.fetchData = function(searchText, options, success) { 2 SomeOtherDDPConnection.call('getPackages', searchText, options, function(err, data) { 3 success(err, data); 4 }); 5};