I have a query like below :
{
"query": {
"bool": {
"filter": [
{
"range": {
"age": {
"from": 57,
"to": null,
}
}
},
{
"terms": {
"_id": [
"1212yas1",
"sdfsfs1"
]
}
}
],
"should": [
{
"query_string": {
"query": "(football) OR (Cricket)",
"default_field": "hobbies.hobby"
}
}
]
}
}
}
I am very new to Elastic Search, I want to implement above query using Java library of Elastic Search how can I do this?
hobbies is nested object, age is long.
CodePudding user response:
First things is that, You need to use IDs
type of query as you are search on _id
field.
If you are using Java high level client then you can use below code:
QueryBuilder query = QueryBuilders.boolQuery().filter(new RangeQueryBuilder("age").from(57))
.filter(new IdsQueryBuilder().addIds("1212yas1", "sdfsfs1"))
.should(new QueryStringQueryBuilder("(football) OR (Cricket)").defaultField("hobbies.hobby"));
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(query);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
If you are using new Java client then you can use below code:
Query query = Query.of(
q -> q.bool(BoolQuery.of(bq -> bq.filter(f -> f.range(RangeQuery.of(rq -> rq.field("age").from("57"))))
.filter(f -> f.ids(IdsQuery.of(iq -> iq.values("1212yas1", "sdfsfs1"))))
.should(s -> s.queryString(QueryStringQuery
.of(qs -> qs.query("(football) OR (Cricket)").defaultField("hobbies.hobby")))))));
CodePudding user response:
If you are using new Java Client Api, try the code bellow:
var query = Query.of(q -> q.bool(BoolQuery.of(bq -> bq
.filter(f -> f
.range(RangeQuery.of(rq -> rq.field("age").from("57"))))
.filter(f -> f
.ids(IdsQuery.of(ids -> ids.values(List.of("1212yas1", "sdfsfs1")))))
.should(s -> s.queryString(
QueryStringQuery.of(qs -> qs.query("(football) OR (Cricket)").defaultField("hobbies.hobby"))))
)));
var response = client.search(SearchRequest.of(sr -> sr
.index("idx_name")
.size(10)
.query(query)
), Entity.class);