2014-10-08 126 views
16

我試圖通過一個簡單的示例應用程序來學習elasticsearch,該應用程序列出了與人相關的報價。這個例子映射可能看起來像:彈性搜索陣列元素的查詢字符串搜索

{ 
    "people" : { 
    "properties" : { 
     "name" : { "type" : "string"}, 
     "quotations" : { "type" : "string" } 
    } 
    } 
} 

一些示例數據可能看起來像:

{ "name" : "Mr A", 
    "quotations" : [ "quotation one, this and that and these" 
       , "quotation two, those and that"] 
} 

{ "name" : "Mr B", 
    "quotations" : [ "quotation three, this and that" 
       , "quotation four, those and these"] 
} 

我想能夠使用個人報價查詢字符串API,並返回匹配誰的人。例如,我可能想要找到包含(這個和這些)引用的人 - 應該返回「A先生」而不是「B先生」,等等。我怎樣才能做到這一點?

EDIT1:

安德烈的回答下面似乎工作,數據值現在看起來像:

{"name":"Mr A","quotations":[{"value" : "quotation one, this and that and these"}, {"value" : "quotation two, those and that"}]} 

不過,我似乎無法獲得QUERY_STRING的查詢工作。以下產生沒有結果:

{ 
    "query": { 
    "nested": { 
     "path": "quotations", 
     "query": { 
     "query_string": { 
      "default_field": "quotations", 
      "query": "quotations.value:this AND these" 
     } 
     } 
    } 
    } 
} 

有沒有辦法讓一個query_string查詢處理嵌套對象?

編輯2:是的,請參閱安德烈的答案。

回答

22

對於要求來實現的,你需要看看嵌套的對象,不要查詢展開的值列表,而是查詢來自該嵌套對象的單個值。例如:

{ 
    "mappings": { 
    "people": { 
     "properties": { 
     "name": { 
      "type": "string" 
     }, 
     "quotations": { 
      "type": "nested", 
      "properties": { 
      "value": { 
       "type": "string" 
      } 
      } 
     } 
     } 
    } 
    } 
} 

值:

{"name":"Mr A","quotations":[{"value": "quotation one, this and that and these"}, {"value": "quotation two, those and that"}]} 
{"name":"Mr B","quotations":[{"value": "quotation three, this and that"}, {"value": "quotation four, those and these"}]} 

查詢:

{ 
    "query": { 
    "nested": { 
     "path": "quotations", 
     "query": { 
     "bool": { 
      "must": [ 
      { "match": {"quotations.value": "this"}}, 
      { "match": {"quotations.value": "these"}} 
      ] 
     } 
     } 
    } 
    } 
} 
+0

我必須將值更改爲:'{「name」:「Mr A」,「quotations」:[{「value」:「引用one,this and that和這些」},{「value」: 「引用二,那些和那個」}]}',但這工作。有沒有辦法使用QueryStringQuery與此?我嘗試使用一個(只是用query_string替換bool),它似乎沒有工作。 – oneway 2014-10-09 13:26:29

+0

你說得對。現在我注意到我拷貝了錯誤的值,即使我使用了正確的值(你提到的)。 – 2014-10-09 13:34:01

+0

試試這個:'{ 「查詢」:{ 「嵌套」:{ 「路徑」: 「語錄」, 「查詢」:{ 「QUERY_STRING」:{ 「default_field」: 「quotations.value」 「查詢」: 「這一點,這些」 }} } } } ' – 2014-10-09 13:36:11

5

不幸的是沒有好的方法來做到這一點。 http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/complex-core-fields.html

當你從一個文檔Elasticsearch回來,任何陣列將在 相同的順序,當您索引文件。您找回的_source字段 包含與您索引的 完全相同的JSON文檔。

但是,數組被索引 - 可搜索 - 作爲無值的多值字段 。在搜索時您不能引用「第一個 元素」或「最後一個元素」。寧可將數組視爲一包 值。

換句話說,它總是考慮數組中的所有值。

這將返回只有A先生

{ 
    "query": { 
    "match": { 
     "quotations": { 
     "query": "quotation one", 
     "operator": "AND" 
     } 
    } 
    } 
} 

但是,這將同時返回先生一& B先生:

{ 
    "query": { 
    "match": { 
     "quotations": { 
     "query": "this these", 
     "operator": "AND" 
     } 
    } 
    } 
} 
+0

使用您的運營商,等我管理。 thnks – 2017-01-09 10:32:41