Geo Distance Search In Elastic Search Liferay 7/DXP
April 26, 2024
Geo Distance Search is used to search the data based on location or nearby location point. For example, If we want all the user details of our website in the area of 100 km from some location point then Geo Distance Search API is very useful.Liferay 7/DXP provides Geo Distance Search API. In this blog, We will use this API to configure Geo Distance Search in Liferay Elastic Search.
Prerequisite:
Basic knowledge about Boolean query, Indexer
Steps to follow:
Step 1: Create Indexer of custom entity.
We have assumed that you have created your custom entity on which you want to apply Geo Distance Search on specific field.
We have also assumed that you have created the indexer of your custom entity
Create Indexer of your custom entity.
For more information, Please go through Liferay documentation for how to create custom indexer.
https://help.liferay.com/hc/en-us/articles/360018157871-Creating-an-Entry-Indexer
Step 2: Add geoLocation field in Indexer:
In your custom entity Indexer class, there is an overridden method called doGetDocument. In which you need to add the geoLocation in document object as below
Set the latitude and longitude values of the location
document.addGeoLocation(latitude, longitude);
There is another overridden method named postProcessSearchQuery. Add the following code to add "geoLocation" as the search term in the method.
addSearchTerm(searchQuery, searchContext, "geoLocation", false);
Step 3: Add the Geo Location Filter in your boolean query
Set the Location Point using GeoLocationPoint:
Set the latitude and longitude values of the location
GeoLocationPoint geoLocationPinPoint = new GeoLocationPoint(latitude, longitude);
Set the Distance using GeoDistance:
Set the radius that you want to cover from the location point. For example, If you want to cover 100 km radius from location point then set geoDistanceValue=100
GeoDistance geoDistance = new GeoDistance(geoDistanceValue, DistanceUnit.KILOMETERS);
Create the object of GeoDistanceFilter:
Pass both geoLocationPinPoint and geoDistance as parameters to create the object of GeoDistanceFilter.
GeoDistanceFilter geoDistanceFilter = new GeoDistanceFilter("geoLocation", geoLocationPinPoint, geoDistance);
Now, Add this Geo Distance Filter in the Boolean query
Create search context object
Then create Boolean Filter by GeoDistanceFilter object
Set the boolean filter in your boolean query.
Finally you will get the hits for the search based on geo distance
SearchContext searchContext = SearchContextFactory.getInstance(request);
BooleanQuery booleanQuery = new BooleanQueryImpl();
...
BooleanFilter booleanFilter = new BooleanFilter();
booleanFilter.add(geoDistanceFilter);
booleanQuery.setPreBooleanFilter(booleanFilter);
...
try {
Hits hits = indexSearcher.search(searchContext, booleanQuery);
} catch (SearchException e) {
// Handle Exception
}
That’s it. You have configured Geo Distance functionality with Liferay7/DXP.