JAVA API is returning five documents when queried for latest doc using custom Id

Hi Folks,

We are trying to fetch latest document (top 1) only but getting five documents in return .We are using JAVA API to do it. Code is as below.

SearchResponse response = client.prepareSearch(index)
.setTypes(type)
.setSearchType(SearchType.QUERY_AND_FETCH)
.setQuery(QueryBuilders.matchQuery(field, value))
.addSort("logID", SortOrder.DESC)
.addSort("postDate", SortOrder.DESC)
.setFrom
.setSize(1).setExplain(true)
.execute()
.actionGet();

Output

Top latest five documents

Hi pDonS,

This is because you are using QUERY_AND_FETCH in your query instead of the default QUERY_THEN_FETCH. Query and fetch's behavior is to retrieve the size from each shard, so since you have 5 shards, you are getting back 5 results.

Additionally we recommend not setting this for your query, see the documentation here: https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-search-type.html#query-and-fetch where this is mentioned to be an internal optimization and should not be explicitly set by the user.

Thanks a lot . Your help is much appreciated