【问题标题】:Is there any way that I could use 'countBy' prefix with my custom query in spring-data-elasticsearch?有什么方法可以在 spring-data-elasticsearch 中使用“countBy”前缀和我的自定义查询?
【发布时间】:2021-06-08 00:31:46
【问题描述】:

我现在在我的 java 项目中使用 spring-bootspring-data-elasticsearch

我必须统计每天报告一些数据的用户数量,所以我为它创建了一个自定义查询,

public interface UserInfoRepository extends ElasticsearchRepository<UserInfo, String> {
    @Query("{\"bool\": {\"must\": [{\"match\": {\"username\": \"?0\"}},{\"range\": {\"createdTime\": {\"gt\": \"now-1d/d\",\"lt\": \"now+1d/d\"}}}]}}")
    List<UserInfo> findByUserNameWithinDayRange(String username);
}

并通过以下代码获取用户数。

private long numberOfUser (String username) {
    List<UserInfo> userInfoWithinADay = suggestionRepository.findByUserNameWithinDayRange(ip);

    return userInfoWithinADay.size();
}

但是,我认为这种方式效率很低;我不需要 UserInfo 的整个列表,只需要它们的“命中”信息。

我能否知道有什么方法可以在我的自定义查询中使用 countBy 前缀,或者使用 spring-data-elasticsearch 发送 Count API?或者有什么方法可以在不定义自定义查询的情况下实现可以在一天范围内找到数据列表的查询?

谢谢!

【问题讨论】:

    标签: java elasticsearch spring-data-elasticsearch


    【解决方案1】:
    1. 您可以使用@CountQuery 代替@Query(或将参数count = true 添加到@Query 注释中)-并将存储库方法的返回值更改为long
    2. 这应该适用于查询派生和像long countByUsernameAndCreatedTimeBetween(String username, Instant from, Instant two) 这样的方法名称 - 我还没有测试过这个。您需要计算日期参数

    我将使用 long userWithinADay(String user) 方法创建一个自定义存储库片段,并在实现中为名称和日期创建一个 CriteriaQuery 并将其传递给 ElasticsearchOperations.count() 方法之一。

    编辑:

    @CountQuery 在 Spring Data Elasticsearch 4.2 中添加。

    【讨论】:

    • 非常感谢,P.J.Meisch。你的答案就是我要找的。如果您不介意,请告诉我在哪里可以得到@CountQuery 注释或在@Query 中使用count=true 参数?似乎我无法导入@CountQuery,并且@Query 注释中不支持count 参数。 (只能找到valuename。)
    • 再问一个问题;你的评论是什么意思? I would create a custom repository fragment with a method long userWithinADay(String user) and in the implementation I would create a CriteriaQuery for the name and the dates and pass that to one of the ElasticsearchOperations.count() methods. 这是否意味着您更喜欢使用 CriteriaQuery 而不是在 ElasticsearchRepository 上使用 Query 注释?再次,非常感谢!
    • 我刚刚编辑了答案,@CountQuery 的更改和@Query 的参数已添加到 Spring Data Elasticsearch 的最新版本中。至于使用CriteriaQuery@Query,这主要是口味问题。我更喜欢第一个,但在您的情况下,使用带注释的查询具有让 Elasticsearch 进行日期数学运算的优势。
    • 哦,我刚刚发现我使用了org.springframework.boot:spring-boot-starter-data-elasticsearch (2.4.5),而不是org.springframework.data:spring-data-elasticsearch。谢谢!
    猜你喜欢
    • 2018-11-06
    • 1970-01-01
    • 2020-04-12
    • 2022-10-20
    • 2018-10-05
    • 2018-08-20
    • 2019-03-10
    • 2019-06-01
    • 1970-01-01
    相关资源
    最近更新 更多