Reputation: 2094
I am new to elastic search , i am reading the doc so far its good but i am not able to write a method to get by range, Below is a method that gets by ID which works perfectly but how can i do this to get a list of data that match the price range.
public Map<String, Object> getTourById(String id){
GetRequest getRequest = new GetRequest(INDEXTOUR, TYPETOUR, id);
GetResponse getResponse = null;
try {
getResponse = restHighLevelClient.get(getRequest);
} catch (java.io.IOException e){
e.printStackTrace();
e.getLocalizedMessage();
}
Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
return sourceAsMap;
}
Above method works fine now below is the method to get by range and return datas that matches the price
public Map<String, Object> getTourByPriceRange(int minPrice, int maxPrice) {
GetRequest getRequest = new GetRequest(INDEXTOUR, TYPETOUR, "requires an ID");
QueryBuilder qb = QueryBuilders
.rangeQuery("price")
.from(minPrice)
.to(maxPrice)
.includeLower(true)
.includeUpper(true);
GetResponse getResponse = null;
try {
getResponse = restHighLevelClient.get(getRequest);
} catch (java.io.IOException e) {
e.printStackTrace();
e.getLocalizedMessage();
}
Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
return sourceAsMap;
}
Only the query builder is accurate in the above method, the result i want to get is a bunch of data that price fall in the range given.
{
"departure": {
"city": "\u0438\u043d\u0441\u043a",
"date": "2018-08-10"
},
"extras": [],
"hotel": {
"beach": {
"distance": 0,
"type": "\u041f\u0435\u0447\u0430\u043d\u044b\u0439"
},
"country": "\u0413\u0440\u0446\u0438\u044f",
"distanceToAirport": 0,
"facilities": [
"Standard Without Balcony"
],
"food": "\u0422\u043e\u043b\u044c\u043a\u043e \u0437\u0430\u0432\u0442\u0440\u0430\u043a\u0438",
"photoUrl": "https://s1.tez-tour.com/hotel/7021893.jpg",
"regionName": "\u0425\u0430\u043b\u043a\u0438\u0434\u0438\u043a\u0438 - \u041a\u0430\u0441\u0441\u0430\u043d\u0434\u0440\u0430",
"stars": 4,
"title": "KALLIKRATEIA"
},
"nights": 8,
"people": 1,
"price": 2595 // i want to use price as parameters for the search method
}
Upvotes: 1
Views: 358
Reputation: 217324
Good job so far!! In order to issue a search request you need to use SearchRequest
and not GetRequest
which is meant to retrieve a single document by ID.
QueryBuilder qb = QueryBuilders
.rangeQuery("price")
.from(minPrice)
.to(maxPrice)
.includeLower(true)
.includeUpper(true);
SearchRequest searchRequest = new SearchRequest(INDEXTOUR);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(qb);
searchRequest.types(TYPETOUR);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = null;
try {
searchResponse = restHighLevelClient.search(searchRequest);
} catch (java.io.IOException e) {
e.printStackTrace();
e.getLocalizedMessage();
}
Upvotes: 3