使用值包含连字符的聚合从 Elasticsearch 检索数据

Retrieve data from Elasticsearch using aggregations where the values contains hyphen

我从事elasticsearch已经有一段时间了...最近遇到了一个问题

我想按弹性搜索索引中的特定列进行分组。该特定列的值包含连字符和其他特殊字符。

SearchResponse res1 = client.prepareSearch("my_index")
            .setTypes("data")
            .setSearchType(SearchType.QUERY_AND_FETCH)
            .setQuery(QueryBuilders.rangeQuery("timestamp").gte(from).lte(to))
            .addAggregation(AggregationBuilders.terms("cat_agg").field("category").size(10))
            .setSize(0)
            .execute()
            .actionGet();

    Terms termAgg=res1.getAggregations().get("cat_agg");
    
    for(Bucket item :termAgg.getBuckets()) {    
        cat_number =item.getKey();
        System.out.println(cat_number+"  "+item.getDocCount());
        }

这是我编写的查询,目的是根据“my_index”中的“类别”列获取数据组。

我在 运行 代码后期望的输出是:

category-1  10

category-2  9

category-3  7

但我得到的输出是:

category   10

1  10

category   9

2  9

category   7

3  7

我已经解决了一些问题,例如 this one,但这些答案无法解决我的问题。

当您索引 "category-1" 时,您将获得(默认情况下)两个术语,"category" 和“1”。因此,当您聚合时,您将得到两个结果。

如果您希望它被视为单个 "term",那么您需要更改索引时在该字段上使用的分析器。将其设置为使用 keyword analyzer

那是因为您的 category 字段有一个默认的字符串映射,它是 analyzed,因此 category-1 被标记为两个标记,即 category1,它解释了您得到的结果。

为了防止这种情况发生,您可以使用以下命令更新您的映射以包含一个将成为 not_analyzed 的子字段 category.raw

curl -XPUT localhost:9200/my_index/data/_mapping -d '{
    "properties": {
        "category": {
            "type": "string",
            "fields": {
                "raw": {
                    "type": "string",
                    "index": "not_analyzed"
                }
            }
        }
    }
}'

在那之后,您需要重新索引您的数据,您的聚合将起作用并且 return 您会如您所愿。 只需确保更改 Java 代码中的以下行:

.addAggregation(AggregationBuilders.terms("cat_agg").field("category.raw").size(10))
                                                                      ^
                                                                      |
                                                                add .raw here