弹性搜索Rails查找带有id的部分记录

时间:2015-06-29 20:16:25

标签: elasticsearch elasticsearch-rails

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

说我有以下记录:

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

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

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

1 个答案:

答案 0 :(得分:1)

其中一种方法是使用edgeNgram filter

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"
            }
         }
      ]
   }
}