有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用包含连字符的聚合从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”中的数据groupby“category”列

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

1类10

2类9

3类7

但我得到的结果是:--

第10类

110

第9类

2.9

第7类

37

我已经浏览了一些链接 “{a1}”等

但这些答案无法解决我的问题

任何帮助都将不胜感激


共 (2) 个答案

  1. # 1 楼答案

    当你索引“category-1”时,你会得到(默认情况下)两个术语,“category”和“1”。因此,当你汇总时,你会得到两个结果

    如果希望将其视为单个“术语”,则需要在索引时更改该字段上使用的分析器。将其设置为使用keyword analyzer

  2. # 2 楼答案

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

    为了防止出现这种情况,可以使用以下命令更新映射以包含子字段category.raw,该子字段将是not_analyzed

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

    在那之后,你需要重新索引你的数据,你的聚合将工作,并返回你所期望的。 只需确保更改Java代码中的以下行:

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