I have an entity stored inside an Elastic Index, one of his fields is an Id (int).
I'm currently using this code to retrieve the data:
var searchRequest = new SearchRequest<MyEntity>(indexName)
{
Size = 1,
Query = new MatchAllQuery(),
Sort = new List<ISort>()
{
new FieldSort(){ Field = "_id", Order = SortOrder.Descending }
}
};
var result = await _elasticClient.SearchAsync<MyEntity>(searchRequest);
var highestId = result.Documents.First().Id;
This code does not return the max Id but it returns the id "999999". What I think its happening is that "_id" in search request it's not the Id inside my entity. What is the correct way to query that value instead?
Edit: I tried of course using "id" (or Id) in the code up above but I get an excpetion
Elasticsearch.Net.UnexpectedElasticsearchClientException : expected:'true | false', actual:'"true"', at offset:639
Also I tried this but I get an id that its even lower that the previous one:
var response = await _elasticClient.SearchAsync<MyEntity>(s => s
.Index(indexName)
.Size(1)
.Aggregations(a =>
a.Max("max_id", x => x.Field("id"))
)
CodePudding user response:
if you use id your entity try this:
GET my-index-000001/_search
{
"size": 0,
"aggs": {
"max_id": {
"max": {
"field": "id"
}
}
}
}
CodePudding user response:
In the end here's the solution:
After the response from @rabbitbr I was able to get this request:
var response = await _elasticClient.SearchAsync<MyEntity>(s => s
.Index(indexName)
.Take(1)
.Aggregations(aggr =>
aggr.Max("get_max_id", max =>
max.Field(field => field.Id)
)
)
);
var highestId = result.Documents.First().Id;
Here my error was NOT the query but how I collected the result: the correct way to get the value of "highestId" is to get from the response the field "Aggregations", then using .Max(aggregationName)
var aggregationName = "get_max_id";
var response = await _elasticClient.SearchAsync<MyEntity>(s => s
.Index(indexName)
.Take(0)
.Aggregations(aggr =>
aggr.Max(aggregationName , max =>
max.Field(field => field.Id)
)
)
);
var highestId = response.Aggregations.Max(aggregationName).Value;