Spring Data ElasticSearch的操作

孔磊
2023-12-01

依赖

		<!--springdata elasticsearch-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

配置文件

#配置es单机版 集群版在后面多加一些节点就行了
spring:
  elasticsearch:
    rest:
      uris:
        - http://xx.xxx.xx.xx:9200

自动注入模板类对象

//注入springdataelasticsearch给我们提供的操作es的模板类对象
    @Autowired  //有的 @Autowired 会自动注入失败 改成 @Resource 就行了
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

创建索引并设置映射

	/**
     * 创建索引,并设置映射
     *
     */
	public void createIndex(){
        //创建索引
        boolean isIndex = elasticsearchRestTemplate.createIndex(TbItem.class);
        System.out.println("创建索引:"+isIndex);

        //创建映射
        boolean isMapping = elasticsearchRestTemplate.putMapping(TbItem.class);
        System.out.println("创建映射:"+isMapping);

    }

删除索引

    /**
     * 删除索引
     */
    public void deleteIndex(){
        //根据指定索引的名称来删除
        boolean isDelete = elasticsearchRestTemplate.deleteIndex("product_item");
        System.out.println(isDelete);
        //根据POJO的字节码对象删除
        boolean b = elasticsearchRestTemplate.deleteIndex(TbItem.class);
        System.out.println(b);
    }

往es中批量增加数据

	/**
	* 往es中批量增加数据
	*/
	public void addAllData(){
        List<TbItem> all = tbItemMapper.findAll();
        ArrayList<IndexQuery> indexQueries = new ArrayList<>();
        for (TbItem tbItem : all) {
//            通过IndexQueryBuilder创建IndexQuery对象
            IndexQuery indexQuery = new IndexQueryBuilder().withObject(tbItem).build();
            indexQueries.add(indexQuery);
        }
//        相当于使用PUT请求,往es中新增数据
        elasticsearchRestTemplate.bulkIndex(indexQueries);
    }

往es中批量增加数据

	/**
	* 往es中新增单条数据
	*/
    public void addData(){
        TbItem item = new TbItem();
        item.setId(23423);
        item.setTitle("迪奥口红");
        item.setPrice(399);
        item.setNum(3);
        item.setSellPoint("涂了之后,她好,我也好");
        //通过IndexQuery构建对象
        IndexQuery indexQuery = new IndexQueryBuilder().withObject(item).build();
        //
        elasticsearchRestTemplate.index(indexQuery);
    }

	/**
     * 删除es中的数据
     */
    public void deleteData(){
        //单条删除:根据id
        String delete = elasticsearchRestTemplate.delete(TbItem.class, "605616");//删除成功会返回被删除商品的id
        System.out.println(delete);
    }

	/**
     * 修改数据
     */
    public void updateData() throws IOException {
        //封装要修改的数据(将你要修改的内容先写好)
        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.doc(XContentFactory.jsonBuilder()
                .startObject()
                .field("title","香奈儿口红")
                .endObject()
        );
        //根据id找到你要修改的目标数据 将数据修改
        UpdateQuery updateQuery = new UpdateQueryBuilder()
                .withUpdateRequest(updateRequest)
                .withClass(TbItem.class)
                .withId("23423").build();
        UpdateResponse update = elasticsearchRestTemplate.update(updateQuery);
    }

全搜索

	/**
     * 全搜索(魔鬼搜索)  但是默认只会搜出来第一页的十条数据
     */
    public void machData(){
    /*
        在SpringData中定义了搜索的接口
        matchAll-->mathchAllQuery()
        match-->mathchQuery()
        range-->rangeQuery()
     */
        SearchQuery searchQuery =new NativeSearchQuery(QueryBuilders.matchAllQuery());
        List<TbItem> tbItems = elasticsearchRestTemplate.queryForList(searchQuery, TbItem.class);
        for (TbItem t : tbItems) {
            System.out.println(t);
        }
    }

条件搜索:IK分词

	/**
     * 条件搜索:IK分词
     */
    public void ikMatchData(){
        SearchQuery searchQuery =new NativeSearchQuery(QueryBuilders.matchQuery("title","口红"));
        List<TbItem> tbItems = elasticsearchRestTemplate.queryForList(searchQuery, TbItem.class);
        for (TbItem t : tbItems) {
            System.out.println(t);
        }
    }

短语搜索:没有任何分词

	/**
     * 短语搜索:没有任何分词
     */
    public void matchPhraseData(){
        SearchQuery searchQuery =new NativeSearchQuery(QueryBuilders.matchPhraseQuery("title","海尔(Haier)HM-M209手机"));
        List<TbItem> tbItems = elasticsearchRestTemplate.queryForList(searchQuery, TbItem.class);
        for (TbItem t : tbItems) {
            System.out.println(t);
        }
    }

term搜索

	/**
     * term搜索
     */
    public void termData(){
        SearchQuery searchQuery =new NativeSearchQuery(QueryBuilders.termsQuery("title","阿尔卡特"));
        List<TbItem> tbItems = elasticsearchRestTemplate.queryForList(searchQuery, TbItem.class);
        for (TbItem t : tbItems) {
            System.out.println(t);
        }
    }

范围搜索

    /**
     * 范围搜索
     */
    public void testRange(){
        SearchQuery searchQuery =new NativeSearchQuery(QueryBuilders.rangeQuery("price").gte(900).lte(3000));
        List<TbItem> tbItems = elasticsearchRestTemplate.queryForList(searchQuery, TbItem.class);
        for (TbItem t : tbItems) {
            System.out.println(t);
        }
    }

多条件搜索:must,should,must_not

    /**
     * 多条件搜索:must,should,must_not
     */
    public void testMulti(){
        //多条件的封装器
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        List<QueryBuilder> must = builder.must();//全部都满足
        must.add(QueryBuilders.matchQuery("sell_point","很好看"));
        must.add(QueryBuilders.rangeQuery("price").gte(900).lte(3000));

        SearchQuery searchQuery =new NativeSearchQuery(builder);
        List<TbItem> tbItems = elasticsearchRestTemplate.queryForList(searchQuery, TbItem.class);
        for (TbItem t : tbItems) {
            System.out.println(t);
        }
    }

分页搜索

    /**
     * 分页搜索
     */
    public void testPage(){
        SearchQuery searchQuery =new NativeSearchQuery(QueryBuilders.matchAllQuery());
        //设置分页
        searchQuery.setPageable(PageRequest.of(0,3));//第1页中查前3条
        //设置排序
        searchQuery.addSort(Sort.by(Sort.Direction.DESC,"price"));//根据价格的降序排序
        List<TbItem> tbItems = elasticsearchRestTemplate.queryForList(searchQuery, TbItem.class);
        for (TbItem t : tbItems) {
            System.out.println(t);
        }
    }
 类似资料: