从另一个索引中不存在 _ids 的索引中搜索文档

时间:2021-06-04 10:16:17

标签: elasticsearch

有没有办法从一个索引中搜索 _ids 在另一个索引中不存在的文档?类似于 MySQL 中的 NOT EXISTS

1 个答案:

答案 0 :(得分:0)

在 elasticsearch 中没有方便的方法来做到这一点,只能通过使用聚合作为一种解决方法:

GET index-a,index-b/_search
{
  "size": 0,
  "aggs": {
    "group_by_id": {
      "terms": {
        "field": "_id",
        "size": 1000
      },
      "aggs": {
        "containied_in_indices_count": {
          "cardinality": {
            "field": "_index"
          }
        },
        "filter_only_differences": {
          "bucket_selector": {
            "buckets_path": {
              "count": "containied_in_indices_count"
            },
            "script": "params.count < 2"
          }
        }
      }
    }
  }
}

然后您需要遍历 group_by_id 聚合中的所有存储桶。考虑使用更大的尺寸,因为它默认为 10,在我的示例中为 1000。如果您的索引存在更多差异,您需要使用此处所述的桶分区:https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html#_filtering_values_with_partitions