How can I pass a JSON query string to a Query builder


(kraythe) #1

I have been trying for hours to get this working. Basically I have a class that performs a filtered query and I want the user to be able to pass a JSON query string to my constructor and then use that on the filtered query to further reduce the results. I have tried all manner of QueryBuilders methods and SearchRequestBuilder methods.

Here is the code I settled on but it doesn't allow custom query:

final SearchRequestBuilder srb = client.prepareSearch(indices).setSearchType(
SearchType.QUERY_AND_FETCH).setTypes(indexTypes);
final GeoDistanceFilterBuilder filter = FilterBuilders.geoDistanceFilter("point").distance(maxDistance, units)
.lat(address.coordinate.latitude).lon(address.coordinate.longitude)
.geoDistance(GeoDistance.ARC);
final GeoDistanceSortBuilder sort = SortBuilders.geoDistanceSort("location.point").geoDistance(
GeoDistance.PLANE).point(address.coordinate.latitude, address.coordinate.longitude);
srb.setQuery(QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), filter));
srb.addSort(sort);

What I would like is something like:

final SearchRequestBuilder srb = client.prepareSearch(indices).setSearchType(
SearchType.QUERY_AND_FETCH).setTypes(indexTypes);
final GeoDistanceFilterBuilder filter = FilterBuilders.geoDistanceFilter("point").distance(maxDistance, units)
.lat(address.coordinate.latitude).lon(address.coordinate.longitude)
.geoDistance(GeoDistance.ARC);
final GeoDistanceSortBuilder sort = SortBuilders.geoDistanceSort("location.point").geoDistance(
GeoDistance.PLANE).point(address.coordinate.latitude, address.coordinate.longitude);
final QueryBuilder query;
if (this.queryJSON == null) {
query = QueryBuilders.fromJSON(this.queryJSON); <<=== doesn't exist.
} else {
query = QueryBuilders.matchAllQuery()
}
srb.setQuery(QueryBuilders.filteredQuery(query, filter));
srb.addSort(sort);

I have tried using srb.setSource() but it completely mangles the JSON putting a comma just inside the first { and not after the query clause. I have tried other methods in search request builder but with no success. Using QueryBuilders.wrapperQuerry(this.queryJSON) doesn't work either.

I have spent hours working on this and would appreciate any pointers.


(system) #2