如何使用java在Elasticsearch中按字段属性搜索文档?

时间:2016-08-30 01:50:18

标签: elasticsearch

enter image description here

我想搜索哪些文档type=0,如何使用java构建搜索查询?

1 个答案:

答案 0 :(得分:3)

您可以使用java中的QueryBuilder构建查询。

以下是相同的示例代码:

BoolQueryBuilder boolQuery = new BoolQueryBuilder();
TermQueryBuilder termQuery = new TermQueryBuilder("tasks.type", 0);
boolQuery.must(termQuery);

然后使用NativeSearchQueryBuilder进行查询,如下面的代码段所示:

NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
            .withIndices("YOUR_INDEX_NAME")
            .withTypes("EVENT_TYPE_NAME").withQuery(boolQuery)
            .withPageable(new PageRequest(0, 60));

SearchQuery searchQuery = queryBuilder.build();

上面的代码段将生成一个搜索查询,以查找值为0的类型字段。

您可以使用ElasticSearchTemplate查询弹性搜索,如下所示:

ElasticSearchTemplate  template = new ElasticSearchTemplate();
.queryForList(searchQuery, YOUR_CLASS.class).forEach(System.err::println);

所以你的最终java代码看起来像这样:

BoolQueryBuilder boolQuery = new BoolQueryBuilder();
TermQueryBuilder termQuery = new TermQueryBuilder("tasks.type", 0);
boolQuery.must(termQuery);
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
        .withIndices("YOUR_INDEX_NAME")
        .withTypes("EVENT_TYPE_NAME").withQuery(boolQuery)
        .withPageable(new PageRequest(0, 60));

SearchQuery searchQuery = queryBuilder.build();
ElasticSearchTemplate  template = new ElasticSearchTemplate();
template.queryForList(searchQuery, YOUR_CLASS.class).forEach(System.err::println);