首页 > 解决方案 > Elasticsearch 查询查找一个字段的重复值并返回另一个字段的值,如 GROUP BY

问题描述

ElasticSearch 6.4 - 给定一个文档索引,其中包含一个名为的字段CaptureId和一个名为 的字段SourceId:我们需要按CaptureId值搜索重复记录。该SourceId字段可以有许多具有相同值的记录,并且我们希望SourceId每组找到的重复项只返回一个。因此,输出将是一个列表SourceIds(每次仅列出一次),其中包含任意数量的重复CaptureId值。

我将如何在 ElasticSearch 中创建此查询?

这是文档映射:

"mappings": {
            "fla_doc": {
                "_field_names": {
                    "enabled": false
                },
                "properties": {
                
                    "captureId": {
                        "type": "long"
                    },
                    "capturedDateTime": {
                        "type": "date"
                    },
                    "language": {
                        "type": "text"
                    },
                    "sourceId": {
                        "type": "long"
                    },
                    "sourceListType": {
                        "type": "text"
                    },
                    "region": {
                        "type": "text"
                    }
                }
            }
        }

标签: elasticsearch

解决方案


假设这两个 ID 字段都是keyworddata type,您可以执行以下操作:

GET index_name/_search
{
  "size": 0,
  "aggs": {
    "by_duplicate_capture": {
      "terms": {
        "field": "CaptureId",
        "min_doc_count": 2
      },
      "aggs": {
        "by_underlying_source_ids": {
          "terms": {
            "field": "SourceId",
            "size": 1
          }
        }
      }
    }
  }
}

如果您对 more 感兴趣SourceIDs,请增加size参数。


推荐阅读