ElasticSearch:在一个请求中检索已过滤和未过滤的计数

时间:2018-01-11 13:09:50

标签: elasticsearch aggregation

我在我的一个ElasticSearch索引中使用以下映射:

"mappings": {
    "my-mapping": {
        "properties": {
            "id": {
                "type": "keyword"
            },
            "groupId": {
                "type" : "keyword"
            }
            "title": {
                "type": "text"
            }
        }
    }
}

我现在想要计算与搜索字符串匹配的元素,搜索字符串可能出现在“title”中,由groupId分组。我可以使用聚合和存储桶实现这一点:

/indexname/_search
{
    "query" : { 
        "term" : { 
            "title" : "sky" 
        }
    },
    "aggs": {
        "filtered_buckets": {
            "terms": {
                "field": "groupId"
            }
        }
    }
}

此外,我想知道所有关于过滤器的 元素的数量。我可以使用非查询搜索来实现这一点:

/indexname/_search
{
    "aggs": {
        "filtered_buckets": {
            "terms": {
                "field": "groupId"
            }
        }
    }
}

目前的问题是:是否有可能在一个请求中生成包含过滤计数的聚合数据和仅在之前有命中的那些组的未过滤计数? 例如:

"buckets": [
    {
        "key": "257786",
        "doc_count": 3024,
        "filtered_doc_count" : 202
    },
    {
        "key": "254640",
        "doc_count": 3010
        "filtered_doc_count" : 1
    },
    {
        "key": "252256",
        "doc_count": 2367
        "filtered_doc_count" : 5
    },
    ...
]

我看到的一种方法是在首先请求所有过滤的桶(它们的ID)然后使用"terms" : { "id" : ["4", "65", "404"] }请求这些特定桶的计数时将请求分成两部分。这不是很好,我不想要求两次(_msearch在这里没有帮助)。

第二个糟糕的解决方案是在我所有实体的某个地方坚持所有计数。

有没有办法实现我在单个请求中描述的内容?

PS:如果问题不清楚,请纠正我。

1 个答案:

答案 0 :(得分:0)

基于这些:

  

How to filter terms aggregation
  http://nocf-www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html

我做了这个:

PUT test
{
  "mappings": {
    "my-mapping": {
        "properties": {
            "id": {
                "type": "keyword"
            },
            "groupId": {
                "type" : "keyword"
            },
            "title": {
                "type": "text"
            }
        }
    }
  }
}

PUT test/type1/1
{
  "id":1,
  "groupId": 1,
  "title": "asd"
}
PUT test/type1/2
{
  "id":2,
  "groupId": 1,
  "title": "sky"
}
PUT test/type1/3
{
  "id":3,
  "groupId": 2,
  "title": "sky"
}
PUT test/type1/4
{
  "id":4,
  "groupId": 2,
  "title": "sky"
}
PUT test/type1/5
{
  "id":5,
  "groupId": 2,
  "title": "sky"
}
POST test/type1/_search
{
  "aggs": {
      "categories-filtered": {            
        "filter": {"term": {"title": "sky"}},
        "aggs": {
          "names": {
            "terms": {"field": "groupId"}
          }
        }
      },
      "categories": {
            "terms": {"field": "groupId"}
      }
    }
}
相关问题