我發現了一些關于范圍查詢和 Elasticsearch 的主題,但這些主題使用了已棄用的高級 REST 客戶端界面。我還在 elasticseach 頁面上找到了一個討論,該頁面使用了新界面,但用于 version 7.15.2。這里的問題是,查詢是由 json 格式的字串構建的,因為此版本不完全支持范圍查詢介面。
不幸的是,當涉及到版本或更高版本的新Java API 客戶端介面時,我在檔案中找不到有用的東西。8.0
我嘗試了以下代碼來獲取多個索引(my-index-*)中的訊息。我設定了與資料庫中使用的格式相對應的日期和時間格式。接下來,我設定時間邊界,from()并且to()存在給定時間段的資料。
// ...
var client = new ElasticsearchClient(...);
var response = client.search(
s -> s.index("my-index-*")
.query(q -> q.range(
r -> r.field("recordtime")
.format("yyyy/MM/dd HH:mm:ss")
.from("2020/01/01 00:00:00")
.to("2020/01/01 00:30:00"))),
JsonNode.class);
當我執行上面的代碼時,我得到以下例外:
Exception in thread "main" co.elastic.clients.elasticsearch._types.ElasticsearchException: [es/search] failed: [search_phase_execution_exception] all shards failed
at co.elastic.clients.transport.rest_client.RestClientTransport.getHighLevelResponse(RestClientTransport.java:281)
at co.elastic.clients.transport.rest_client.RestClientTransport.performRequest(RestClientTransport.java:147)
at co.elastic.clients.elasticsearch.ElasticsearchClient.search(ElasticsearchClient.java:1526)
at co.elastic.clients.elasticsearch.ElasticsearchClient.search(ElasticsearchClient.java:1543)
at // the function including the line of code above.
這些是我build.gradle對應于 elasticsearch 的依賴項。
dependencies {
// ...
implementation group: 'co.elastic.clients', name: 'elasticsearch-java', version: '8.1.0'
implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.13.0'
// ...
}
那么,我做錯了什么?我更喜歡使用構建器 API 的方式,而不是創建 json-string 將其轉換為JsonData-object 并將其傳遞給ElasticsearchClient客戶端。
我現在還嘗試使用 curl 請求查詢搜索并使用以下行:
curl -X GET -k -u elastic:$ESPASS "https://<es-server-url>:9200/my-index-*/_search"
-H 'Content-Type: application/json' -d'{
"query": {
"range": {
"recordtime": {
"format": "yyyy/MM/dd HH:mm:ss",
"from": "2020/01/29 00:00:00",
"to": "2020/01/29 00:30:00"
}
}
}
}'
在這里,我從服務器獲取資料。
uj5u.com熱心網友回復:
好的,我發現了錯誤。
我搞砸了日期格式。更正后,我得到了 Java API 的結果。
上述問題的代碼按預期作業。但是在我的真實代碼中,我使用了一個函式來獲取定時欄位的格式。好吧,函式回傳的格式是,dd/MM/yyyy HH:mm:ss但正確的格式是(如問題中所寫)yyyy/MM/dd HH:mm:ss。如您所見,我交換了日子和年份。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/446604.html
標籤:爪哇 弹性搜索 elasticsearch-java-api 范围查询
