登录    关于
马育民老师的博客

马育民的博客

QQ:65242847

springboot 使用 Spring Data Elasticsearch 高级查询文档

上接:springboot 使用 Spring Data Elasticsearch 操作 Elasticsearch 7.9-创建工程

查询操作

package top.malaoshi.ctrl;

import org.elasticsearch.common.lucene.search.function.FieldValueFactorFunction;
import org.elasticsearch.index.query.*;
import org.elasticsearch.index.query.functionscore.FieldValueFactorFunctionBuilder;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.metrics.MaxAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.ParsedMax;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.*;
import org.springframework.data.elasticsearch.core.query.*;
import es.entity.Toutiao;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class SearchCtrl {

    @Autowired
    private ElasticsearchRestTemplate temp;
    /**
     * term 查询加分页
     */
    @RequestMapping("/termQueryByPage")
    public void termQueryByPage() {
        //term查询
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title.keyword", "JAVA技巧");
        //设置查询分页,从第一页开始,一页显示10条,从0开始
        PageRequest page = PageRequest.of(0, 10);
        //按照点赞数量降序排序
        SortBuilder sort=SortBuilders.fieldSort("like").order(SortOrder.DESC);
        NativeSearchQuery query=new NativeSearchQueryBuilder()
                .withQuery(termQueryBuilder)
                .withPageable(page)
                .withSort(sort)
                .build();
        SearchHits<Toutiao> shs = temp.search(query,Toutiao.class);
        System.out.println("共:"+shs.getTotalHits()+" 条记录!");
        for (SearchHit<Toutiao> item : shs) {
            Toutiao toutiao=item.getContent();
            System.out.println(toutiao);
        }
    }
    /**
     模糊查询
     */
    @RequestMapping("/wildcard")
    public void wildcard(){
        // 关键字查询
        QueryBuilder wildcard=QueryBuilders.wildcardQuery("title.keyword","*技巧*");
        //设置查询分页,从第一页开始,一页显示10条,从0开始
        PageRequest page = PageRequest.of(0, 10);
        //按照点赞数量降序排序
        SortBuilder sort=SortBuilders.fieldSort("like").order(SortOrder.DESC);
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withQuery(wildcard);
        nativeSearchQueryBuilder.withPageable(page);
        SearchHits<Toutiao> shs=temp.search(nativeSearchQueryBuilder.build(),Toutiao.class);
        for(SearchHit<Toutiao> item : shs){
            Toutiao toutiao=item.getContent();
            System.out.println(toutiao);
        }
    }
    /**
     * 匹配查询
     */
    @RequestMapping("/match")
    public void match(){
        //match查询
        QueryBuilder match=QueryBuilders.matchQuery("title","java mysql");
        //设置查询分页,从第一页开始,一页显示10条,从0开始
        PageRequest page=PageRequest.of(0,10);
        //按照点赞数量降序排序
        SortBuilder sort=SortBuilders.fieldSort("like").order(SortOrder.DESC);
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(match)
                .withPageable(page)
                .withSort(sort)
                .build();
        SearchHits<Toutiao> shs=temp.search(query,Toutiao.class);
        for(SearchHit<Toutiao> item : shs){
            Toutiao toutiao=item.getContent();
            System.out.println(toutiao);
        }
    }
    /**
     * bool 查询
     */
    @RequestMapping("/bool")
    public void bool() {
        //1.创建QueryBuilder(即设置查询条件)这儿创建的是组合查询(也叫多条件查询),后面会介绍更多的查询方法
        /*组合查询BoolQueryBuilder
         * must(QueryBuilders)   :AND
         * mustNot(QueryBuilders):NOT
         * should:               :OR
         */
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        //设置要查询博客的标题中含有关键字
        builder.must(new MatchQueryBuilder("title","入门"));
        builder.must(new MatchQueryBuilder("content","技巧"));
        //按照点赞数量降序排序
        SortBuilder sort = SortBuilders.fieldSort("like").order(SortOrder.DESC);
        //设置查询分页,从第一页开始,一页显示10条,从0开始
        PageRequest page = PageRequest.of(0, 10);
        //2.构建查询
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(builder)
                .withPageable(page)
                .withSort(sort)
                .build();
        //3.执行查询
        SearchHits<Toutiao> shs = temp.search(query,Toutiao.class);
        //4.获取总条数(用于前端分页)
        long total =  shs.getTotalHits();
        //5.获取查询到的数据内容(返回给前端)
        for(SearchHit<Toutiao> item:shs){
            Toutiao toutiao=item.getContent();
            System.out.println(toutiao);
        }
    }
    /**
     * 范围查询
     */
    @RequestMapping("/range")
    public void range(){
        QueryBuilder match=QueryBuilders.matchQuery("content","java");
        //大于229,小于等于983
        QueryBuilder range=QueryBuilders.rangeQuery("like").gt(229).lte(983);
        BoolQueryBuilder bool=QueryBuilders.boolQuery();
        bool.must(match);
        bool.filter(range);
        //设置查询分页,从第一页开始,一页显示10条,从0开始
        PageRequest page=PageRequest.of(0,10);
        //按照点赞数量降序排序
        SortBuilder sort=SortBuilders.fieldSort("like").order(SortOrder.DESC);
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(bool)
                .withPageable(page)
                .withSort(sort)
                .build();
        SearchHits<Toutiao> shs=temp.search(query,Toutiao.class);
        for(SearchHit<Toutiao> item : shs){
            Toutiao toutiao=item.getContent();
            System.out.println(toutiao);
        }
    }
    @RequestMapping("/aggs")
    public void aggs(){
        MaxAggregationBuilder max= AggregationBuilders.max("max_like").field("like");
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .addAggregation(max)
                .build();
        SearchHits<Toutiao> shs=temp.search(query,Toutiao.class);
        Aggregations aggregations = shs.getAggregations();
        ParsedMax agg=aggregations.get("max_like");
        double val=agg.getValue();
        System.out.println(val);
    }
    /*
    二次评分
     */
    @RequestMapping("/functionScore")
    public void functionScore(){
        PageRequest page=PageRequest.of(0,10);
        MatchQueryBuilder mqb=QueryBuilders.matchQuery("title", "java");
        FieldValueFactorFunctionBuilder fffb=ScoreFunctionBuilders.fieldValueFactorFunction("like")
                .modifier(FieldValueFactorFunction.Modifier.LOG1P);
        // 分数,并自动按分排序(对单个属性进行查询)
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.
                functionScoreQuery(mqb,fffb);
        Query query = new NativeSearchQueryBuilder()
                .withQuery(functionScoreQueryBuilder)
                .withPageable(page)
                .build();
        SearchHits<Toutiao> shs = temp.search(query, Toutiao.class);
        List<SearchHit<Toutiao>> list=shs.getSearchHits();
        for(SearchHit<Toutiao> item:list){
            Toutiao toutiao=item.getContent();
            System.out.println(item.getScore()+"--"+toutiao);
        }
    }
    @RequestMapping("/test2")
    public void test2(){
        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                //查询条件
                .withQuery(QueryBuilders.queryStringQuery("java mysql").defaultField("title"))
                //分页
                .withPageable(PageRequest.of(0, 5))
                //排序
                .withSort(SortBuilders.fieldSort("like").order(SortOrder.DESC))
                //高亮字段显示
                .withHighlightFields(new HighlightBuilder.Field("java mysql"))
                .build();
        SearchHits<Toutiao> shs = temp.search(nativeSearchQuery, Toutiao.class);
        List<SearchHit<Toutiao>> list=shs.getSearchHits();
        for(SearchHit<Toutiao> item:list){
            Toutiao toutiao=item.getContent();
            System.out.println(toutiao);
        }
    }
}

原文出处:https://malaoshi.top/show_1IX1tOTe226Q.html