要不要也来分享分享一下啊

elasticsearch的java api如何使用查询模板

Elasticsearch | 作者 tr0217 | 发布于2015年05月17日 | 阅读数:9612

这是使用模板进行查询的代码
public class QueryText {

public static void main(String[] args) {
try (Node node = NodeBuilder.nodeBuilder()
.clusterName("net.01")
.client(true).node()) {
//创建elastic客户端
Client client = node.client();

//读取查询模板,然后设置参数查询
try (BufferedReader bodyReader = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\common.template"), "utf8"))) {
String line = null;
StringBuilder strBuffer = new StringBuilder();
while ((line = bodyReader.readLine()) != null) {
strBuffer.append(line);
strBuffer.append("\n");
}

Map<String, Object> search_params = new HashMap<>();
search_params.put("from", 1);
search_params.put("size", 5);
search_params.put("key_words", "opencv sift");

QueryBuilder qb = QueryBuilders.templateQuery(strBuffer.toString(), search_params);
SearchResponse sr;
SearchRequestBuilder srb;
srb = client.prepareSearch("blog_v1")
.setTypes("blogpost")
.setQuery(qb);
sr = srb.get();

for (SearchHit hit : sr.getHits().getHits()) {
System.out.println(hit.getSourceAsString());
}
} catch (UnsupportedEncodingException ex) {

} catch (FileNotFoundException ex) {

} catch (IOException ex) {

}

}
}
}

模板是这个样子的
{
"template": {
"query": {
"function_score": {
"query": {
"multi_match": {
"query": "{{key_words}}",
"type": "best_fields",
"fields": [
"title^3",
"body",
"tag^2",
"category^2"
],
"tie_breaker": 0.3,
"minimum_should_match": "75%"
}
},
"field_value_factor": {
"field": "views",
"modifier": "log1p"
}
}
},
"fields": [
"tag",
"category",
"url"
],
"highlight": {
"pre_tags": [
"<em>"
],
"post_tags": [
"</em>"
],
"fields": {
"title": {
"fragment_size": 32,
"number_of_fragments": 1
},
"body": {
"fragment_size": 80,
"number_of_fragments": 1
}
}
}
}
}
可是from和size,以及控制返回的Fields和highlight都没有起作用。还是默认的返回最开始10天,还是返回了文档的全文。
已邀请:

xling - 一句话介绍

赞同来自:

from和size的问题解决了没?

要回复问题请先登录注册