如何在Elasticsearch中查询属性有值的记录?



我试图在我的Elasticsearch中搜索所有记录,其中字段images具有值?images类型为object

我试了下面的

GET /records/_search
{
"query": {
"exists": {
"field": "images"
}
}
}

,我还尝试了以下

GET /records/_search
{
"query": {
"bool": {
"must": {
"exists": {
"field": "images"
}
}
}
}
}

但是上面的两个调用返回0。

但是,当我执行以下命令时,我得到images

的记录
GET /records/_doc/8875352
"images" : [
{
"path" : "1/8875352/1.jpg",
"is_preferred" : false,
"object_id" : 1
},
{
"path" : "1/8875352/2.jpg",
"is_preferred" : false,
"object_id" : 2
},
{
"path" : "1/8875352/3.jpg",
"is_preferred" : false,
"object_id" : 3
},
{
"path" : "1/8875352/4.jpg",
"is_preferred" : false,
"object_id" : 4
},
{
"path" : "1/8875352/5.jpg",
"is_preferred" : false,
"object_id" : 5
},
{
"path" : "1/8875352/6.jpg",
"is_preferred" : false,
"object_id" : 6
},
{
"path" : "1/8875352/7.jpg",
"is_preferred" : false,
"object_id" : 7
},
{
"path" : "1/8875352/8.jpg",
"is_preferred" : false,
"object_id" : 8
}
]

您可以使用下面的查询

找到images至少有1个值的所有记录
{
"query": {
"exists": {
"field": "images.path"
}
}
}

或者您可以使用脚本来过滤数据

{
"query": {
"bool": {
"filter": {
"script": {
"script": {
"source": "doc['images.path.keyword'].length > 0",
"lang": "painless"
}
}
}
}
}
}

事实证明我的第一个查询实际上是正确的

GET /records/_search
{
"query": {
"exists": {
"field": "images"
}
}
}

问题是images字段没有索引。索引是这样创建的

PUT /records
{
"mappings":{
"properties":{
"tags":{
"type":"keyword"
},
"summary":{
"type":"text"
},
"@timestamp":{
"type":"date"
},
"images":{
"type":"object",
"enabled":false
}
}
}
}

请注意,"enabled":false将禁用该字段的索引,从而使其无法搜索。

最新更新