当前位置: 首页 > 工具软件 > RESTClient > 使用案例 >

RestClient

林修真
2023-12-01

目录

初始化javaRestClient

RestClient操作索引库

RestClient操作文档

排序,高亮,分页,复合查询

Boolean Query

Function Query


初始化javaRestClient

引入es的RestHiggLeveClient依赖

<!-- elasticsearch-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
        </dependency>

因为SpringBoot默认的ES版本是7.6.2,所以需要覆盖默认的ES版本:

<properties>
        <elasticsearch.version>7.12.1</elasticsearch.version>
    </properties>

初始化RestClient

@SpringBootApplication
public class HotelDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(HotelDemoApplication.class, args);
    }
    @Bean
    public RestHighLevelClient client() {
        return new RestHighLevelClient(RestClient.builder(
                //es集群地址
                HttpHost.create("http://192.168.80.130:9200"),
                HttpHost.create("http://192.168.80.131:9200")
        ));
    }
}

RestClient操作索引库

  • 创建索引库:client.indices().create()
  • 删除索引库:client.indices().delete()
  • 校验索引库是否存在:client.indices().exists()

创建索引库,例: 

import org.elasticsearch.client.indices.CreateIndexRequest;

    @Autowired
    private RestHighLevelClient client;
    
    @Test
    void createhotelindex() throws IOException {
        //创建request对象
        CreateIndexRequest request = new CreateIndexRequest("索引库");
        //准备请求参数:DSL语句
        request.source("DSL语句", XContentType.JSON);
        //发起请求
        client.indices().create(request, RequestOptions.DEFAULT);
    }

RestClient操作文档

  1. 添加文档:client.index()
  2. 查询文档:client.get()
  3. 删除文档:client.delete()
  4. 修改文档:
  • 全量修改:client.index()
  • 增量修改:client.update()

添加文档

/**
     * 将数据库中的数据添加es索引库
     */
    @Test
    void documentaddtest() throws IOException {
        Hotel hotel = iHotelService.getById(36934L);
        HotelDoc hotelDoc = new HotelDoc(hotel);
        IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
        request.source(JSON.toJSONString(hotelDoc),XContentType.JSON);
        client.index(request,RequestOptions.DEFAULT);
    }

批量添加文档

@Test
    void documentBatchtest() throws IOException {
        //准备对象
        BulkRequest request = new BulkRequest();
        // 查询数据库中的数据
        List<Hotel> hotels = iHotelService.list();
        //通过Steam流添加多条数据
        hotels.stream().map(item -> {
            HotelDoc hotelDoc = new HotelDoc(item);
            request.add(new IndexRequest("hotel")
                    .id(hotelDoc.getId().toString())
                    .source(JSON.toJSONString(hotelDoc),XContentType.JSON));
            return item;
        }).collect(Collectors.toList());
        //发起请求
        client.bulk(request,RequestOptions.DEFAULT);
    }

查询文档

@Test
    void documentgettest() throws IOException {
        GetRequest request = new GetRequest("索引库","id");
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        //获取源数据
        String json = response.getSourceAsString();
        //反序列化为对象
        HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
        System.out.println(hotelDoc);
    }

删除文档

@Test
    void documentdeletetest() throws IOException {
        DeleteRequest request = new DeleteRequest("索引库","id");
        client.delete(request,RequestOptions.DEFAULT);
    }

增量修改文档

@Test
    void documentupdatetest() throws IOException {
        UpdateRequest request = new UpdateRequest("hotel","36934");
        Map<String,Object> map = new HashMap<>();
        map.put("starName","三钻");
        map.put("price",337);
        request.doc(map);
        client.update(request,RequestOptions.DEFAULT);
    }

排序,高亮,分页,复合查询

解析文档数据

    void resulthits(SearchResponse response) {
        //获取数据条数
        long total = response.getHits().getTotalHits().value;
        //获取文档
        SearchHit[] hits = response.getHits().getHits();
        HotelDoc hotelDoc = new HotelDoc();
        for (SearchHit searchHit: hits) {
            //获取文档source
            String json = searchHit.getSourceAsString();
            //反序列化为对象
            hotelDoc = JSON.parseObject(json, HotelDoc.class);
            //获取文档高亮数据
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            //判断是否做高亮处理
            if (!(CollectionUtils.isEmpty(highlightFields))){
                //获取字段名为name的高亮数据
                HighlightField name = highlightFields.get("name");
                //判断是否高亮name字段
                if (name != null){
                    //获取高亮值
                    Text[] fragments = name.getFragments();
                    //覆盖原始的name字段
                    hotelDoc.setName(fragments[0].toString());
                }
            }
            System.out.println(hotelDoc);
        }
    }

Boolean Query

@Test
    void testbool() throws IOException {
        //准备request,连接索引库
        SearchRequest request = new SearchRequest("hotel");
        BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
         //TODO 查询坐标在31.21,121.5附件10km的价格不高于400的如家酒店的前五家酒店,且对距离做升序排序
        queryBuilder.must(QueryBuilders.termQuery("brand","如家"))//查询brand为如家品牌
                .mustNot(QueryBuilders.rangeQuery("price").gte(400))//;//price不高于400
                .filter(QueryBuilders//过滤
                        .geoDistanceQuery("location")//字段名
                        .point(31.21,121.5)//经纬度 先纬度后经度
                        .distance(10, DistanceUnit.KILOMETERS));//前:半径长度,后:单位km
        //准备dsl语句
        request.source()
                .query(queryBuilder)//查询
                //高亮处理
                .highlighter(new HighlightBuilder()
                        .requireFieldMatch(false)
                        .field("name")
                        .preTags("<em>")
                        .postTags("</em>"))
                //分页处理
                .from(0)//分页起始位置
                .size(5)//每页的数量
                .sort(SortBuilders
                        .geoDistanceSort("location",new GeoPoint(31.21,121.5))//字段名 ,中心点坐标
                        .order(SortOrder.ASC)//升序排序
                        .unit(DistanceUnit.KILOMETERS));//单位KM
        //发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        
        //解析文档数据
        resulthits(response);
        
    }

Function Query

@Test
    void search() throws IOException {
        SearchRequest requset = new SearchRequest("hotel");
        //算分控制
        //TODO 给isAD字段为true的酒店的算分结果都乘10
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                //原始查询
                QueryBuilders.matchQuery("all", "速8"),
                //function score数组
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        //其中的一个function score的元素
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                //过滤条件
                                QueryBuilders.termQuery("isAD",true),
                                //算分函数(规则)
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                });
        requset.source().query(functionScoreQuery);
        //分页
        requset.source().from((0)).size(5);
        SearchResponse response = client.search(requset, RequestOptions.DEFAULT);
        //解析响应
        resulthits(response);
    }

 类似资料: