如何使用lunr.js进行搜索

时间:2016-07-15 13:06:36

标签: lunrjs

lunr.js的工作方式与下面格式的数据相似

[{
      'id': { 'id': 614, 'value': 1 },
      'first_name': { 'id': 244, 'value': 'Johnny' },
      'last_name': { 'id': 724, 'value': 'Fields' },
      'email': { 'id': 567, 'value': 'jfields0@barnesandnoble.com' },
      'gender': { 'id': 220, 'value': 'Male' },
      'age': { 'id': 745, 'value': 18 }
    }, {
      'id': { 'id': 204, 'value': 2 },
      'first_name': { 'id': 163, 'value': 'Kathy' },
      'last_name': { 'id': 991, 'value': 'Gilbert' },
      'email': { 'id': 453, 'value': 'kgilbert1@over-blog.com' },
      'gender': { 'id': 184, 'value': 'Female' },
      'age': { 'id': 337, 'value': 50 }
    }]

但是当数据如下所示时不会。

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $compile) {
  'use strict';

  $scope.data = {
    "name": ""
  };

  $scope.reset = function() {
    $scope.data.name = "";
    $scope.form.$setPristine();

  }
  $scope.reset1 = function() {
    $scope.data.name1 = "";
    $scope.form1.$setPristine();

  }


});

有关如何索引数据以使其正常工作的任何提示。

1 个答案:

答案 0 :(得分:2)

添加到lunr的文档应采用与答案第一部分格式相似的形式,如果您的数据具有其他结构,那么您将不得不将其转换为lunr可以理解的内容。

假设您的索引定义如下所示:

var idx = lunr(function () {
  this.ref('id')
  this.field('first_name')
  this.field('last_name')
  this.field('email')
  this.field('gender')
  this.field('age')
})

然后,在将文档添加到索引之前,您需要通过以下函数映射它:

var mapDocument = function (doc) {
  return Object.keys(doc).reduce(function (memo, key) {
    memo[key] = doc[key].value
    return memo
  }, {})
}

该功能有效地展平整个文档,您可能希望限制实际从文档中提取的字段,但希望您能够理解。然后,上述函数将转换您的文档:

  {
    'id': { 'id': 614, 'value': 1 },
    'first_name': { 'id': 244, 'value': 'Johnny' },
    'last_name': { 'id': 724, 'value': 'Fields' },
    'email': { 'id': 567, 'value': 'jfields0@barnesandnoble.com' },
    'gender': { 'id': 220, 'value': 'Male' },
    'age': { 'id': 745, 'value': 18 }
  }

对于lunr可以理解的事情:

  {
    'id': 1,
    'first_name': 'Johnny',
    'last_name': 'Fields',
    'email': 'jfields0@barnesandnoble.com',
    'gender': 'Male',
    'age': 18
  }