首页 > 解决方案 > 根据数组计数过滤弹性数据

问题描述

我们如何从以下索引数据中获取至少有一个电话号码以及其他条件(如必须和应该)的候选人?

使用弹性版本 6.*

        {
            "_index": "test",
            "_type": "docs",
            "_id": "1271",
            "_score": 1.518617,
            "_source": {
                "record": {
                    "createdDate": "2020-10-16T10:49:51.53",
                    "phoneNumbers": [
                        {
                            "type": "Cell",
                            "id": 0,
                            "countryCode": "+1",
                            "phoneNumber": "7845200448",
                            "extension": "",
                            "typeId": 700
                        }
                    ]
                },
                "entityType": "Candidate",                   
                "dbId": "1271",
                "id": "1271"
            }
        }

标签: elasticsearchfilter

解决方案


您可以使用术语查询来返回在提供的字段中包含一个或多个确切术语的文档。

搜索查询:

{
  "query": {
    "bool": {
      "must": [
        {
          "terms": {
            "record.phoneNumbers.phoneNumber.keyword": [
              "7845200448"
            ]
          }
        }
      ]
    }
  }
}

搜索结果:

"hits": [
      {
        "_index": "stof_64388591",
        "_type": "_doc",
        "_id": "1",
        "_score": 1.0,
        "_source": {
          "record": {
            "createdDate": "2020-10-16T10:49:51.53",
            "phoneNumbers": [
              {
                "type": "Cell",
                "id": 0,
                "countryCode": "+1",
                "phoneNumber": "7845200448",
                "extension": "",
                "typeId": 700
              }
            ]
          },
          "entityType": "Candidate",
          "dbId": "1271",
          "id": "1271"
        }
      }
    ]

更新 1:适用于版本 7。 *

您需要使用脚本查询,根据提供的脚本过滤文档。

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

对于版本 6。 *

{
  "query": {
    "bool": {
      "filter": {
        "script": {
          "script": {
            "source": "doc['record.phoneNumbers.phoneNumber.keyword'].values.length > 0",
            "lang": "painless"
          }
        }
      }
    }
  }
}

推荐阅读