2014-01-07 62 views
0

我正在嘗試通過姓或名查找具有相同building_id的人。
例如,某人將在可能是名字或姓氏的文本字段中輸入名稱。他們都擁有相同的建築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 
     } 
    }, 
... 
... 
+0

那麼你到目前爲止嘗試過什麼? – Mureinik

回答

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 
}' 

然後,如果你想在2號樓搜索所有的「泰勒」 S,執行以下命令:

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,並在本地主機上運行:9200):

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

+0

令人驚歎。爲什麼'filter'中的'query'和'term'中的'multi_match'?爲了做到這一點,他們都需要「過濾」? – Johnston

+1

這就是您設置過濾查詢的方式:http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-filtered-query.html。我直接跟着這個例子。唯一令人困惑的是整個結構必須進入「查詢」模塊。 –

+2

基本思想是過濾後的查詢包含查詢和過濾器。過濾器將阻止不符合某些標準的文檔,並且比其他類型的查詢更有效。過濾後的查詢不是實現所需內容的唯一方法,這只是首先想到的。 –