引入依赖

  <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        <version>2.7.0</version>
    </dependency>

构建BoolQueryBuilder进行条件查询

1. 精确匹配

  QueryBuilders.matchQuery("name",”小明”);

2.模糊查询

2.1.常用的字符串查询--左右模糊
QueryBuilders.queryStringQuery("fieldValue").field("fieldName");

2.2前缀查询 如果字段没分词,就匹配整个字段前缀
 
QueryBuilders.prefixQuery("fieldName","fieldValue");

2.3多字段模糊查询

String[] fieldName = new String[2];

fieldName[0] = "明";

fieldName[1] = "年";

QueryBuilders.moreLikeThisQuery(fieldName);

2.4 wildcard query

通配符查询,支持* 任意字符串;?任意一个字符

QueryBuilders.wildcardQuery("fieldName","ctr*");

QueryBuilders.wildcardQuery("fieldName","c?r?");

2.5 自动分词模糊查询

QueryBuilders.matchQuery("keywordCh", "小米")

2、多条件查询

2.1 and、or、not

组合查询BoolQueryBuilder

  must(QueryBuilders)  :AND

  mustNot(QueryBuilders) :NOT

  should:        :OR


builder.must(QueryBuilders.queryStringQuery("年轻").field("author"));
 builder.should(QueryBuilders.matchQuery("count",1));

3、排序查询


FieldSortBuilder sort = SortBuilders.fieldSort("count").order(SortOrder.ASC);

4、一个字段匹配多个值
builder.must(QueryBuilders.termsQuery("desc", "年","书"));

5、一个值匹配多个字段
 builder.must(QueryBuilders.multiMatchQuery("小", "author", "desc"));

6、范围查询
闭区间查询
QueryBuilder queryBuilder0 = QueryBuilders.rangeQuery("fieldName").from("fieldValue1").to("fieldValue2");

开区间查询

QueryBuilder queryBuilder1 = QueryBuilders.rangeQuery("fieldName").from("fieldValue1").to("fieldValue2").includeUpper(false).includeLower(false);//默认是true,也就是包含

大于

QueryBuilder queryBuilder2 = QueryBuilders.rangeQuery("fieldName").gt("fieldValue");

大于等于

QueryBuilder queryBuilder3 = QueryBuilders.rangeQuery("fieldName").gte("fieldValue");

小于

QueryBuilder queryBuilder4 = QueryBuilders.rangeQuery(“fieldName”).lt(“fieldValue”);

小于等于

QueryBuilder queryBuilder5 = QueryBuilders.rangeQuery("fieldName").lte("fieldValue");

构建执行

   @Autowired
   private ElasticsearchOperations operations;
    NativeSearchQuery build = nativeSearchQueryBuilder.withQuery(boolQueryBuilder)
            .withPageable(page)
            .withSort(createTimeSort)
            .build();
    SearchHits<ESProjects> search = operations.search(build, ESProjects.class);

真理求知者
4 声望0 粉丝

在黑暗在探索光明,在迷茫中寻找真理!


« 上一篇
高级sql使用