Spring 中的 ElasticSearch 与 @Query

标签 elasticsearch spring-boot elasticsearch-plugin spring-data-elasticsearch

我已经使用 ElasticSearch 的 _plugin/head 接口(interface)成功创建了一个查询。该查询旨在返回特定位置特定设备的最新时间戳。查询如下所示:

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

上述查询按预期工作。 现在使用 Spring-Boot 和 Spring-Data-ElasticSearch,我定义了自己的 ElasticSearchRepository,如下所示:

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

上面的代码有问题,主要是因为我希望它返回一个 DeviceEvent,但它实际上返回了一个设备事件,计数 = 10(默认页面大小)。似乎结果也没有按时间戳降序排列。就好像查询的 sizeorder 部分没有被拾取。

我在这里做错了什么?

最佳答案

而不是在查询注释中控制结果大小。

使用Pageable接口(interface),以下摘自文档

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

这将使您能够:

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

如果你也想排序:

findByName("foo-name", new PageRequest(0,1, new Sort(new Sort.Order(Sort.Direction.ASC,"name")))).getContent().get(0);

关于Spring 中的 ElasticSearch 与 @Query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28797075/

相关文章:

java - Spring Boot中未创建MongoDB唯一索引

elasticsearch - Elasticsearch 聚合和详细信息

grails - 对Grails中的Elastic Search结果调用findBy…时发生TransientObjectException

elasticsearch - 如何在elasticsearch中查询上个月的数据

elasticsearch - 无法为带有错误消息的索引创建映射设置

elasticsearch - Elasticsearch匹配数组用法

spring-boot - 如何将 @Transcational 与 spring-data-cosmosdb 一起使用?

mysql - Spring boot Multi-Tenancy ,一个租户连接到多个模式

elasticsearch - 如何从字段中获取特定大小的结果?