Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ElasticSearch in Spring with @Query

I have successfully created a query using ElasticSearch's _plugin/head interface. The query is meant to return the latest timestamp for a specific device at a specific location. The query looks as follows:

{  
   "query":{  
      "bool":{  
         "must":[  
            {  
               "term":{  
                  "deviceevent.location.id":"1"
               }
            },
            {  
               "term":{  
                  "deviceevent.deviceId":"AHE1LDD01"
               }
            }
         ]
      }
   },
   "from":0,
   "size":1,
   "sort":{  
      "timestamp":{  
         "order":"desc"
      }
   }
}

The above query works as intended. Now using Spring-Boot and Spring-Data-ElasticSearch, I defined my own ElasticSearchRepository which looks as follows:

package com.repository.elasticsearch;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import com.domain.DeviceEvent;

public interface DeviceEventRepository extends ElasticsearchRepository<DeviceEvent, String>
{
    @Query("{\"bool\":{\"must\":[{\"term\":{\"deviceevent.location.id\": \"?0\"}},{\"term\":{\"deviceevent.deviceId\": \"?1\"}}]}},\"from\": 0,\"size\": 1,\"sort\":{\"timestamp\":{\"order\":\"desc\"}}")
    DeviceEvent findLatestCheckInAtLocation(Long locationId, String deviceId);
}

The above code is breaking mainly because I would expect it to return one DeviceEvent, but it's actually returning a device events with count = 10 (The default Page size). It seems also that the results are not being ordered by the timestamp in a descending order. It's as if the size and order parts of the query are not being picked up.

What am I doing wrong here?

like image 400
Mouhammed Soueidane Avatar asked Feb 10 '23 19:02

Mouhammed Soueidane


1 Answers

Instead of controlling the results size in the query annotation.

Use the Pageable interface, the following is taken from the documentation.

public interface BookRepository extends ElasticsearchRepository<Book, String> {
    @Query("{"bool" : {"must" : {"field" : {"name" : "?0"}}}}")
    Page<Book> findByName(String name,Pageable pageable);
}

This would allow you to:

findByName("foo-name", new PageRequest(0,1));

If you want to sort also:

findByName("foo-name", new PageRequest(0,1, new Sort(new Sort.Order(Sort.Direction.ASC,"name")))).getContent().get(0);
like image 170
JayTee Avatar answered Feb 13 '23 22:02

JayTee