简体   繁体   中英

Java Elastic search: getting the last ID of an index

I'm using Elastic Search 7.5.1 and it's Java client. I'm inserting in my index using ints as _id and I have to increment it manually. For that, I need to retrieve the last ID inserted. I know how to do it using PostMan:

GET my_index/_search

{
  "size": 1, 
  "query": {
    "match_all": {}
  },
 "sort": [{
      "_id": {
        "order": "desc"
      }
    }
  ]
}

But I don't know how to do it using their Java client . I'm trying with the code below but it's returning one of those auto-generated IDs. My index has only 3 items with Ids 1,2 and 3.

private static String getLastElastticSearchId(String index)
{
    RestHighLevelClient client = getElasticSearchClient();

    SearchRequest searchRequest = new SearchRequest();
    SearchSourceBuilder b = new SearchSourceBuilder();
    b.query(QueryBuilders.matchAllQuery());
    b.sort(new FieldSortBuilder("_id").order(SortOrder.DESC));
    b.from(0);
    b.size(1);
    searchRequest.source(b);

    try {

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = searchResponse.getHits();

        if(hits.getTotalHits().value > 0){
            SearchHit[] searchHits = hits.getHits();
            for (SearchHit hit : searchHits) {
                return hit.getId();
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

How to can I change my code to get the last ID?

Thanks

I just found what was wrong. I had to tell in which index to look for when instantiating the request:

SearchRequest searchRequest = new SearchRequest(index);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM