Search code examples
springspring-bootelasticsearchspring-data-elasticsearch

Spring Data Elasticsearch Query Merge


I have a application for get a location from given points' 10 km radius and I have two filters for query; first is query by customer no and the second one is query by filtered items location according to. I want to combine elastic custom query and spring data method name based query. How can I merge them?

My document:

import lombok.Getter;
import lombok.Setter;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.GeoPointField;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Getter
@Setter
@Document(indexName = "customer", replicas = 0, refreshInterval = "-1")
public class Customer {

    @GeneratedValue(strategy= GenerationType.AUTO)
    @Id
    private String id;

    private Integer cifNo;

    private String userId;

    private String name;

    private Integer locationCount;

    private Date lastSeenDate;

    @GeoPointField
    private GeoPoint geoPoint;

}

Repository;

@Repository
public interface CustomerLocationRepository extends ElasticsearchRepository<CustomerLocation,Long> {
    List<CustomerLocation> findByCifNoAndUserIdIsNullOrderByLastSeenDateDesc(Integer cifNo);
    List<CustomerLocation> findByCifNoAndUserIdOrderByLastSeenDateDesc(Integer clientNo, String userId);
}

Service:

public List<CustomerLocation> getCustomersPlacesIndexWithinLocation(GenericRequest genericRequest) {
    GeoDistanceQueryBuilder geoDistanceQueryBuilder = QueryBuilders
            .geoDistanceQuery("geoPoint")
            .point(genericRequest.getLatitude(),genericRequest.getLongitude())
            .distance(10, DistanceUnit.KILOMETERS);

    List<CustomerLocation> customerLocationList;

    if(genericRequest.getUserId()!=null) {
        customerLocationList = customerLocationRepository.findByCifNoAndUserIdOrderByLastSeenDateDesc(Integer.valueOf(genericRequest.getClientNo()),genericRequest.getUserId());
    } else {
        customerLocationList = customerLocationRepository.findByCifNoAndUserIdIsNullOrderByLastSeenDateDesc(Integer.valueOf(genericRequest.getClientNo()));
    }

    SearchQuery searchQuery = new NativeSearchQueryBuilder()
            .withFilter(geoDistanceQueryBuilder)
            .build();

    return elasticsearchTemplate.queryForList(searchQuery,CustomerLocation.class);
}

How can I combine spring data elasticsearch query result with custom location search query?


Solution

  • Currently this is not possible with Spring Data Elasticsearch. I added a Jira issue for this to be implemented as a new feature.