查询所有
//搜索全部文档 QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
查询单个,等于/eq
//单个匹配,搜索name为li的文档 QueryBuilder queryBuilder = QueryBuilders.matchQuery("name", "li");
查询多个字段匹配某一个值
//搜索name中或nickname中包含有li的文档(必须与li一致) QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery("li","name", "nickname");
模糊匹配
//搜索名字中含有li文档(name中只要包含li即可) WildcardQueryBuilder queryBuilder = QueryBuilders.wildcardQuery("name","*li*");
BoolQueryBuilder复合查询
BoolQueryBuilder对象使用must方法build,多个and使用多个must
WildcardQueryBuilder queryBuilder1 = QueryBuilders.matchQuery("name", "li"); WildcardQueryBuilder queryBuilder2 = QueryBuilders.matchQuery("id", "1"); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); //查询名字是LI和id是1的所有数据 boolQueryBuilder.must(queryBuilder1); boolQueryBuilder.must(queryBuilder2);
BoolQueryBuilder对象使用should方法build,多个or使用多个should使用
WildcardQueryBuilder queryBuilder1 = QueryBuilders.matchQuery("name", "li"); WildcardQueryBuilder queryBuilder2 = QueryBuilders.matchQuery("id", "1"); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); //查询名字是LI或id是1的所有数据 boolQueryBuilder.should(queryBuilder1); boolQueryBuilder.should(queryBuilder2);
must:必须满足的条件 should:非必须满足的条件 minimumShouldMatch(1):至少要满足一个 should 条件
等值查询
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.termQuery("name", "小李"));
范围查询
BoolQueryBuilder queryBuilder = QueryBuilders.rangeQuery("age").gte(18).lte(50);
判空查询
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery() .must(QueryBuilders.existsQuery("name")) .mustNot(QueryBuilders.existsQuery("tag")); //查询name有值,tag不存在值
分页查询
SearchResponse response = this.transportClient .prepareSearch(index) .setTypes(type) .setQuery(queryBuilder) .setFrom(offset) .setSize(rows) .setExplain(false) .execute() .actionGet();
本篇文章如有帮助到您,请给「翎野君」点个赞,感谢您的支持。