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

尧思齐 发布于 2015/05/17 17:07
阅读 7K+
收藏 1

@纳兰琴 你好,想跟你请教个问题:


这是使用模板进行查询的代码

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天,还是返回了文档的全文。

加载中
0
纳兰琴
纳兰琴

1. from 和 size 在模板里没有

2. 设置了Fields你应该用 hit.getFields().get("title").value() ,而不是hit.getSourceAsString()

3. 高亮的没问题,hit.getHighlightFields()

尧思齐
尧思齐
你好 ,谢谢解答。 1、这个和我测试的结果一致。 2、好像也不能通过模板设置Fields,我用模板设置了不起作用,因为getFields没有结果,getSource返回了所有字段。通过代码直接设置是可以的。 3、高亮应该也不能通过模板设置,也只有通过代码。 这样看起来好像,查询模板并没有太大的作用。
返回顶部
顶部