【问题标题】:ElasticSearch in Spring with @Query在 Spring 中使用 @Query 进行 ElasticSearch
【发布时间】:2015-05-02 01:18:10
【问题描述】:

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

{  
   "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 部分没有被拾取。

我在这里做错了什么?

【问题讨论】:

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


    【解决方案1】:

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

    使用Pageable接口,以下摘自文档。

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

    【讨论】:

    • 按时间戳排序呢?
    • 已更新排序。
    • 非常感谢!我也对你的回答做了一些修改。
    猜你喜欢
    • 1970-01-01
    • 2020-06-11
    • 2016-04-11
    • 2021-04-21
    • 2022-12-05
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多