我有一组文档(类型'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
字段)(见 issue ),如果 object
类型 ES 压扁嵌套字段(参见 nested type 、 object type )。这就是为什么我建议改为查询叶元素之一。但它要求其中之一是强制性的(不幸的是,您的情况不满足)。
无论如何,我使用 source_filtering 中的 _source
参数找到了解决方案。 :
"must_not": {
"script": {
"script": "_source.locations.size() > 0"
}
}
注意使用 "lang":"groovy"
你应该写:"script": "_source.locations.size > 0"
关于arrays - 在 ElasticSearch 上搜索具有空数组字段的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26737665/