[英]Search document with empty array field, on ElasticSearch
我有一組文檔(類型為'article' ),我想在數組字段中搜索包含元素/對象的文檔
{
"_type": "article",
"_source": {
"title": "Article 1",
"locations": [
{
"address": "ES headquarter",
"city": "Berlin"
}
]
}
}
我想要兩個查詢(只有一個,但有一點變化):
我嘗試了不同的方法,但可能我對 ElasticSearch 太差了:
{
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": [
{
"type": {
"value": "article"
}
},
{
"bool": {
"must_not": {
"missing": {
"field": "location",
"existence": true,
"null_value": true
}
}
}
}
]
}
}
}
這不起作用。
但主要是:
如果address
是location
數組中的必填字段,則可以修改查詢:
"must_not": {
"missing": {
"field": "locations.address"
}
}
AFAIK,在ES中,您無法查詢非葉元素(如您的location
字段)(請參閱問題 ),如果object
類型ES扁平化嵌套字段(請參閱嵌套類型 , 對象類型 )。 這就是我建議查詢其中一個葉元素的原因。 但它要求其中一個是強制性的(遺憾的是,在您的情況下不滿意)。
無論如何,我在source_filtering中使用_source
參數找到了解決方案:
"must_not": {
"script": {
"script": "_source.locations.size() > 0"
}
}
注意使用"lang":"groovy"
你應該寫: "script": "_source.locations.size > 0"
它似乎已經回答了類似的問題,我沒有測試解決方案,但是你可以嘗試一下:>> elasticsearch根據一個數組的字段大小進行過濾 。
根據 Elasticsearch 文檔
空數組被視為缺失字段——沒有值的字段。
假設您在article-index
索引中有兩個文檔
# First document
{
"_type": "article",
"_source": {
"title": "Article 1",
"locations": [{"address": "ES headquarter", "city": "Berlin"}]
}
}
# Second document
{
"_type": "article",
"_source": {
"title": "Article 2",
"locations": []
}
}
預期的查詢將是:
GET article-index/_search
{
"query": {
"exists": {
"field": "locations"
}
}
}
GET article-index/_search
{
"query": {
"bool": {
"must": {
"exists": {
"field": "locations"
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.