Home > OS >  How to create subfield keyword for Aggregation in ElasticSearch
How to create subfield keyword for Aggregation in ElasticSearch

Time:01-20

I am trying to get Aggregation results from ElasticSearch index

For exmaple , values in my index

"_source": {
"ctry": "abc", 
"totalentry": 1,
"entrydate": "2022-01-06"
},
"_source": {
"ctry": "abc", 
"totalentry": 3,
"entrydate": "2022-01-07"
},
"_source": {
"ctry": "xyz", 
"totalentry": 1,
"entrydate": "2022-01-08"
}

expected Results should be get totalentry based on country

ctry : abc
totalentry : 4
ctry : xyz
totalentry : 1

My Aggreagtion query

  QueryBuilder querybuilder = QueryBuilders.boolQuery().must(QueryBuilders.rangeQuery("entrydate")
                .gte("2022-01-01").lte ("2022-01-31"));      
      TermsAggregationBuilder groupBy = AggregationBuilders.terms("ctry").field("ctry");
      SearchQuery searchQuery = new NativeSearchQueryBuilder()
                        .withQuery(querybuilder).addAggregation(groupBy)
                        .build();
       List<Sample> records = elasticsearchRestTemplate.queryForList(searchQuery, Sample.class);

Above aggregation query returning 3 records instead of 2 aggregated results. My index properties

"ctry": {
"type": "keyword"

How to change it to below , so that i hope i will get correct aggregation results

ctry": {
"type": "text",
"fields": {
"keyword": {
"ignore_above": 256,
"type": "keyword"
}
}
}

My java code

@Document(indexName="sample", createIndex=true, shards = 4)
public class Sample { 

     @Field(type = FieldType.Keyword)
     private String ctry;

CodePudding user response:

You are using an outdated version of Spring Data Elasticsearch. The queryForList variants were deprecated in 4.0 and have been removed in 4.2.

You need to use one of the search...() methods that return a SearchHits<Sample>> object. That will contain the documents for your query and the aggregations.

  •  Tags:  
  • Related