按名字或姓氏和具体相关ID搜索?

时间:2014-01-07 17:20:38

标签: java search jdbc elasticsearch

我试图通过名字或名字找到一个人,他们都拥有相同的building_id。
例如,有人会在文本字段中输入名称,该名称可能是名字或姓氏。他们都拥有相同的建筑ID。我似乎无法在弹性搜索的文档中找到它。 我的结果数据如下所示:

{
    took: 9,
    timed_out: false,
    _shards: {
        total: 5,
        successful: 5,
        failed: 0
    },
    hits: {
        total: 56,
        max_score: 1,
        hits: [
    {
        _index: "jdbc",
        _type: "jdbc",
        _id: "5",
        _score: 1,
        _source: {
            first_name: "some first name",
            last_name: "some last name",
            building_id: 1
        }
    },
...
...

1 个答案:

答案 0 :(得分:2)

一种方法是使用带有term查询的multi_match过滤器。为了说明,首先创建一些文档:

curl -XPUT "http://localhost:9200/test_index"

curl -XPUT "http://localhost:9200/test_index/person/1" -d'
{
   "first_name": "Bob",
   "last_name": "Jones",
   "building_id": 1
}'

curl -XPUT "http://localhost:9200/test_index/person/2" -d'
{
   "first_name": "Bill",
   "last_name": "Smith",
   "building_id": 1
}'

curl -XPUT "http://localhost:9200/test_index/person/3" -d'
{
   "first_name": "Joe",
   "last_name": "Williams",
   "building_id": 2
}'

curl -XPUT "http://localhost:9200/test_index/person/4" -d'
{
   "first_name": "John",
   "last_name": "Taylor",
   "building_id": 2
}'

curl -XPUT "http://localhost:9200/test_index/person/5" -d'
{
   "first_name": "Taylor",
   "last_name": "Johnson",
   "building_id": 2
}'

然后,如果要搜索Building 2中的所有“Taylor”,请执行以下操作:

curl -XPOST "http://localhost:9200/test_index/person/_search" -d'
{
   "query": {
      "filtered": {
         "query": {
            "multi_match": {
               "query": "taylor",
               "fields": [
                  "first_name",
                  "last_name"
               ]
            }
         },
         "filter": {
            "term": {
               "building_id": 2
            }
         }
      }
   }
}'

你会得到结果:

{
   "took": 2,
   "timed_out": false,
   "_shards": {
      "total": 2,
      "successful": 2,
      "failed": 0
   },
   "hits": {
      "total": 2,
      "max_score": 0.94125634,
      "hits": [
         {
            "_index": "test_index",
            "_type": "person",
            "_id": "5",
            "_score": 0.94125634,
            "_source": {
               "first_name": "Taylor",
               "last_name": "Johnson",
               "building_id": 2
            }
         },
         {
            "_index": "test_index",
            "_type": "person",
            "_id": "4",
            "_score": 0.5906161,
            "_source": {
               "first_name": "John",
               "last_name": "Taylor",
               "building_id": 2
            }
         }
      ]
   }
}

这是一个可运行的示例(您需要在您的计算机上安装Elasticsearch并在localhost:9200上运行):

http://be6c2e3260c3e2af000.qbox.io/gist/cc47b232ec60f09b93906a5c80028c1317dbdf28