ElasticSearch-获取多次

aq13

可以说我在Elasticsearch中有一些数据,我想检索一个特定字段不止一次出现的所有记录。例如:

{id:1, name: "bob", "age":30}
{id:2, name: "mike", "age":20}
{id:3, name: "bob", "age":30}
{id:4, name: "sarah", "age":40}
{id:5, name: "mike", "age":35}

我想要一个按名称返回多次出现的查询。因此,它应该返回以下记录:

{id:1, name: "bob", "age":30}
{id:2, name: "mike", "age":20}
{id:3, name: "bob", "age":30}
{id:5, name: "mike", "age":35}

编号:4被排除在外,因为名称“ sarah”仅出现在一个文档中。更可取的回报是:

{"name": "bob", "count":2}
{"name": "mike", "count":2}

但可以更轻松地使用第一个查询返回。

提姆

您可以使用AggregationsElasticsearch中所谓的东西如果您只是在寻找重复的名称,则可以使用Terms Aggregation

这是一个例子。您可以这样设置数据:

PUT testing/_doc/1
{
  "name": "bob",
  "age": 30
}

PUT testing/_doc/2
{
  "name": "mike",
  "age": 20
}

PUT testing/_doc/3
{
  "name": "bob",
  "age": 30
}

PUT testing/_doc/4
{
  "name": "sarah",
  "age": 40
}

PUT testing/_doc/5
{
  "name": "mike",
  "age": 20
}

然后运行您的聚合:

GET testing/_doc/_search
{
  "size": 0,
  "query": {
    "match_all": {}
  },
  "aggs": {
    "duplicates": {
      "terms": {
        "field": "name.keyword",
        "min_doc_count": 2
      }
    }
  }
}

这将给您这样的响应:

{
  "took": 6,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 5,
    "max_score": 0,
    "hits": []
  },
  "aggregations": {
    "duplicates": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "bob",
          "doc_count": 2
        },
        {
          "key": "mike",
          "doc_count": 2
        }
      ]
    }
  }
}

重要的部分是aggregations.duplicates.buckets"name"显示的"key"

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章