【问题标题】:How to define a query timeout for a spring data elastic search query?如何为弹簧数据弹性搜索查询定义查询超时?
【发布时间】:2019-06-09 15:02:38
【问题描述】:
我的问题更笼统,假设我有一个像这样的简单查询来弹性搜索
Page<MyEntity> findAll(Pageable pageable);
例如,我希望能够为此查询设置超时,这样它就不会永远挂起,尽管我阅读了文档,但我没有看到任何关于如何做到这一点的明确信息。
有什么办法吗?一种为 Spring-data-elasticsearch 查询设置超时的方法,我可以确保什么都不会得到太长时间?
【问题讨论】:
标签:
spring
spring-data
spring-data-elasticsearch
【解决方案1】:
在搜索请求查询中实现“超时”的一种方法是在查询本身中使用 “超时”参数。 here
假设我们要执行全文“匹配查询”,我们可以在查询本身之前添加“超时”:
{
"timeout": "1ms",
"query": {
"match" : {
"description" : "This is a fullText test"
}
}
}
您必须使用提到的 Elasticsearch 时间单位 here 并将它们作为字符串值发送。
在你的情况下 - 我看不出有任何方法可以使用 spring-data-es 存储库来实现这一点,但是 - 你可以向你的存储库添加自定义功能并将 ElasticsearchIndexTemplate 与 matchAllQuery( ) (java 弹性 api),
类似的东西(没有测试过):
nodeEsTemplate.getClient().prepareSearch("test-index")
.setQuery(QueryBuilders.matchAllQuery())
.setTimeout(TimeValue.timeValueMillis(1))
.execute().actionGet();
由于 nodeEsTemplate 是 ElasticsearchIndexTemplate 类型,并且假设您在存储库类中创建了自定义 findAllWithTimeOut 方法。