0

我正在尝试使用 Rails 和 Elastic Search 使用 elasticsearch-rails gem 实现自动完成。

假设我有以下记录:

[{id: 1, name: "John White"}, 
 {id:2, name: "Betty Johnson"}]

在搜索“John”时,我可以使用哪种弹性搜索方法来返回两条记录。

自动完成只会返回“John White”,并且不会返回 id:1。

4

1 回答 1

2

一种方法是使用edgeNgram 过滤器

PUT office
{
  "settings": {
    "analysis": {
      "analyzer": {
        "default_index":{
          "type":"custom",
          "tokenizer":"standard",
          "filter":["lowercase","edgeNgram_"]
        }
      },
      "filter": {
        "edgeNgram_":{
          "type":"edgeNgram",
          "min_gram":"2",
          "max_gram":"10"
        }
      }
    }
  },
  "mappings": {
    "employee":{
      "properties": {
        "name":{
          "type": "string"
        }
      }
    }
  }
}

PUT office/employee/1
{
  "name": "John White"
}
PUT office/employee/2
{
  "name": "Betty Johnson"
}
GET office/employee/_search
{
  "query": {
    "match": {
      "name": "John"
    }
  }
}

结果将是:

{
   "took": 5,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 2,
      "max_score": 0.19178301,
      "hits": [
         {
            "_index": "office",
            "_type": "employee",
            "_id": "1",
            "_score": 0.19178301,
            "_source": {
               "name": "John White"
            }
         },
         {
            "_index": "office",
            "_type": "employee",
            "_id": "2",
            "_score": 0.19178301,
            "_source": {
               "name": "Betty Johnson"
            }
         }
      ]
   }
}
于 2015-06-29T20:36:12.147 回答