ElasticSearch in Spring with @Query

旧街凉风 提交于 2019-12-23 20:15:22

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/28797075/elasticsearch-in-spring-with-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!