簡體   English   中英

在 ElasticSearch 上搜索具有空數組字段的文檔

[英]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
              }
            }
          }
        }
      ]
    }
  }
}

這不起作用。

  • 您將如何解決我的查詢?

但主要是:

  • 您將如何搜索具有空數組字段的文檔?

如果addresslocation數組中的必填字段,則可以修改查詢:

"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"

如果您不想啟用腳本,可以將Exists查詢must_not bool查詢結合使用,例如:

{
  "query":{
    "bool":{
      "must_not":[
        {
          "exists":{
            "field":"tags"
          }
        }
      ]
    }
  }
}

它似乎已經回答了類似的問題,我沒有測試解決方案,但是你可以嘗試一下:>> 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": []
    }
}

預期的查詢將是:

  1. 獲取所有有位置的文章
GET article-index/_search
{
  "query": {
    "exists": {
       "field": "locations"
    }
  }
}
  1. 獲取所有沒有位置的文章
GET article-index/_search
{
  "query": { 
    "bool": {
      "must": {
        "exists": {
          "field": "locations"
        }
      }
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM