[英]Spring Data Elasticsearch query by JSON structure
我正在使用spring數據elasticsearch,當我使用@Query注釋時,將代碼與實際的JSON elasticsearch查詢相關聯要容易得多,如此鏈接引用中的示例所示:
我想知道是否有一種方法可以通過不帶注釋的elasticsearch java庫通過完整的JSON主體進行查詢。 IE中的方法實現或其他東西。 這將幫助我解析響應中的突出顯示等。
感謝您提供任何信息。
評論澄清:我正在使用Spring-data-elasticsearch 3.0.10.RELEASE和Elasticsearch 6.由於spring-data-elasticsearch似乎還不支持RestHighLevelClient,我使用的是TransportClient客戶端= new PreBuiltTransportClient(elasticsearchSettings) ; 創建ElasticsearchTemplate時的方法:return new ElasticsearchTemplate(client());
我想出了一種方法,但它要求你制作一個存在於Elastic節點上的腳本。 請參閱基於文件的腳本 。 它不是非常靈活,但要試一試。 這是做什么的。
創建名為template_doctype.mustache
的文件並將其復制到$ELASTIC_HOME/config/scripts
。 這是您可以根據需要定制的腳本。 重新啟動Elastic或等待60秒以重新加載。
{
"query" : {
"match" : {
"type" : "{{param_type}}"
}
}
}
我的pom.xml
依賴項:
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>3.0.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.5.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
<scope>compile</scope>
</dependency>
</dependencies>
(僅供參考,我發現使用mvn dependency:tree
,你的spring-data-elasticsearch
elasticsearch版本隱含地使用了5.5版本的ElasticSearch庫,即使你使用的是ElasticSearch 6.)
創建虛擬索引:
curl -X PUT http://localhost:9200/myindex
創建幾個可用於匹配的文檔以確保代碼有效:
curl -X POST http://localhost:9200/myindex/mydoc -d '{"title":"foobar", "type":"book"}'
curl -X POST http://localhost:9200/myindex/mydoc -d '{"title":"fun", "type":"magazine"}'
嘗試運行查詢。 此代碼應返回單個文檔:
String clusterName = "my-application";
Settings elasticsearchSettings = Settings.builder().put("cluster.name", clusterName).build();
TransportClient client = new PreBuiltTransportClient(elasticsearchSettings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"),9300));
Map<String, Object> template_params = new HashMap<>();
// Here is where you put parameters to your script.
template_params.put("param_type", "book");
SearchResponse sr = new SearchTemplateRequestBuilder(client)
.setScript("template_doctype") // this is where you specify what template to use
.setScriptType(ScriptType.FILE)
.setScriptParams(template_params)
.setRequest(new SearchRequest())
.get()
.getResponse();
SearchHit[] results = sr.getHits().getHits();
for(SearchHit hit : results){
String sourceAsString = hit.getSourceAsString();
if (sourceAsString != null) {
Gson gson = new GsonBuilder().setPrettyPrinting()
.create();
Map map = gson.fromJson(sourceAsString, Map.class);
System.out.println( gson.toJson(map));
}
}
輸出:
{
"title": "foobar",
"type": "book"
}
這是另一種方法,但不使用傳輸客戶端。
將這些依賴項添加到您的pom.xml
:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.19</version>
<scope>compile</scope>
</dependency>
然后這樣做:
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
Client client = new Client();
final WebResource r = client.resource("http://localhost:9200").path("/myindex/_search");
String requestJson = "{\"query\" : {\"match\" : {\"type\" : \"book\"} }}";
ClientResponse response = r.post(ClientResponse.class, requestJson);
String json = response.getEntity(String.class);
Gson gson = new GsonBuilder().setPrettyPrinting()
.create();
Map map = gson.fromJson(json, Map.class);
System.out.println(gson.toJson(map));
// to convert to SearchResponse:
JsonXContentParser xContentParser = new JsonXContentParser(NamedXContentRegistry.EMPTY,
new JsonFactory().createParser(json));
SearchResponse searchResponse = SearchResponse.fromXContent(xContentParser);
示例輸出:
{
"took": 9.0,
"timed_out": false,
"_shards": {
"total": 5.0,
"successful": 5.0,
"failed": 0.0
},
"hits": {
"total": 1.0,
"max_score": 0.2876821,
"hits": [
{
"_index": "myindex",
"_type": "mydoc",
"_id": "AWXp8gZjXyu6lA_2Kpi2",
"_score": 0.2876821,
"_source": {
"title": "foobar",
"type": "book"
}
}
]
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.