2016-09-19 27 views
0

我想查詢所有匹配任何下列值,這些文件匹配陣列的任何可能的確切值:Elasticsearch,在Array

["Test","Cat","Dog"] 
在字段類別

我有以下映射:

"categories": { 
    "type": "string" 
} 

幾個樣本文件都

"categories": [ 
    "Test", 
    "Cat" 
] 

或者

"categories": [ 
    "Blue Cat", 
    "Ball" 
] 

我可以用下面的查詢,把它關閉:

query: { 
    match: { 
     categories: { 
      query: ["Test","Cat","Dog"] 
     } 
    } 

但是,這將返回我這兩個文件,因爲他們都包括「貓」即使他們其中之一包括它的形式「藍貓」,我怎麼能指定他們我想要的確切值「貓」不是它包括它?

我讀到了關於將映射上的字段類型更改爲嵌套的方法,但是由於數組沒有鍵和值,因此不接受它作爲嵌套對象。

如果我用這個映射:

"categories": { 
    "type": "nested" 
} 

我得到這個錯誤:

"object mapping for [categories] tried to parse field [null] as object, but found a concrete value" 

我怎麼能由現場類別使用可能值的數組,並確保它至少匹配濾波器其中一個值是什麼?

回答

2

將字段更改爲「not_analyzed」。現在它使用一個默認的「標準」分析器,將「藍貓」分成兩個標記「藍色」和「貓」,這就是爲什麼你的查詢匹配包含「藍貓」的文檔。

這裏是映射

{ 
"categories": { 
    "type":  "string", 
    "index": "not_analyzed" 
}} 

我使用上述映射索引兩個文件。

{ 
_index : "test_index", 
_type : "test", 
_id : "2", 
_score : 1, 
_source : { 
    categories : [ 
     "Blue Cat", 
     "Ball" 
    ] 
}}, { 
_index : "test_index", 
_type : "test", 
_id : "1", 
_score : 1, 
_source : { 
    categories : [ 
     "Test", 
     "Cat"] 
}}]} 

我搜索使用下面的模板

{ 
"query" : { 
    "constant_score" : { 
     "filter" : { 
      "terms" : { 
       "categories" :["Test","Cat","Dog"] 
      } 
     } 
    } 
}} 

我回來只有第一個文件

{ 
"took" : 9, 
"timed_out" : false, 
"_shards" : { 
    "total" : 5, 
    "successful" : 5, 
    "failed" : 0 
}, 
"hits" : { 
    "total" : 1, 
    "max_score" : 1, 
    "hits" : [{ 
      "_index" : "test_index", 
      "_type" : "test", 
      "_id" : "1", 
      "_score" : 1, 
      "_source" : { 
       "categories" : [ 
        "Test", 
        "Cat" 
       ] 
      } 
     } 
    ] 
}}