java使用spring-data-elasticsearch实现全文检索(查询/分页/排序/聚合)

1.maven

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
        </dependency>
</dependencies> 

2.pojo对象

@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "ppp",shards = 1,createIndex = false)
public class Item {
    @Field(type = FieldType.Long)
    @Id
    Long id;
    @Field(type = FieldType.Text,analyzer = "ik_smart")
    String title; //标题
    @Field(type = FieldType.Keyword)
    String category;// 分类
    @Field(type = FieldType.Keyword)
    String brand; // 品牌
    @Field(type = FieldType.Double)
    Double price; // 价格
    @Field(type = FieldType.Keyword,index = false)
    String images; // 图片地址
}

3.yml文件配置elasticsearch

如何搭建ES请 点击此处

spring:
  elasticsearch:
    rest:
      uris: http://192.168.233.128:9200  # 这里改成你自己的es服务器地址

4.测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class EsTest {


    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;


    @Autowired
    ItemRepository itemRepository;

    @Test
    public void createIndex() throws IOException {
        // 1 获取索引对象
        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(Item.class);
        // 2 创建索引
        indexOperations.create();
//        // 3 获取映射
        Document mapping = indexOperations.createMapping(Item.class);
        // 4 将映射放入索引
        indexOperations.putMapping(mapping);
        boolean exists = indexOperations.exists();
        System.out.println(exists);
        // 5 删除索引
//        indexOperations.delete();
    }

    @Test
    public void indexList() {
        List<Item> list = new ArrayList<>();
        list.add(new Item(1L, "小米手机7", "手机", "小米", 3299.00, "http://image.leyou.com/13123.jpg"));
        list.add(new Item(2L, "坚果手机R1", "手机", "锤子", 3699.00, "http://image.leyou.com/13123.jpg"));
        list.add(new Item(3L, "华为META10", "手机", "华为", 4499.00, "http://image.leyou.com/13123.jpg"));
        list.add(new Item(4L, "小米Mix2S", "手机", "小米", 4299.00, "http://image.leyou.com/13123.jpg"));
        list.add(new Item(5L, "荣耀V10", "手机", "华为", 2799.00, "http://image.leyou.com/13123.jpg"));
        // 接收对象集合,实现批量新增
        itemRepository.saveAll(list);
    }

    @Test
    public void find() {
        Iterable<Item> all = itemRepository.findAll();
        for (Item item : all) {
            System.out.println(item);
        }
    }

    @Test
    public void findByPriceBetween() {
        Iterable<Item> all = itemRepository.findItemByPriceBetween(2000.00, 4299.00);
        for (Item item : all) {
            System.out.println(item);
        }
    }

    @Test
    public void cud() {
        List<Item> list = new ArrayList<>();
        list.add(new Item(1L, "小米手机7", "手机", "小米", 3299.00, "http://image.leyou.com/13123.jpg"));
        list.add(new Item(2L, "坚果手机R1", "手机", "锤子", 3699.00, "http://image.leyou.com/13123.jpg"));
        list.add(new Item(3L, "华为META10", "手机", "华为", 4699.00, "http://image.leyou.com/13123.jpg"));
        list.add(new Item(4L, "华为META11", "手机", "华为", 4799.00, "http://image.leyou.com/13123.jpg"));
        list.add(new Item(5L, "vivo", "手机", "华为", 4099.00, "http://image.leyou.com/13123.jpg"));
        list.add(new Item(6L, "OPPO", "手机", "华为", 4499.00, "http://image.leyou.com/13123.jpg"));
        list.add(new Item(7L, "中兴META14", "手机", "华为", 4599.00, "http://image.leyou.com/13123.jpg"));
        list.add(new Item(8L, "华为META15", "手机", "华为", 4199.00, "http://image.leyou.com/13123.jpg"));
        list.add(new Item(9L, "华为META16", "手机", "华为", 4299.00, "http://image.leyou.com/13123.jpg"));
        list.add(new Item(10L, "华为META17", "手机", "华为", 4399.00, "http://image.leyou.com/13123.jpg"));
        elasticsearchRestTemplate.save(list);
        // 根据id删除
//        elasticsearchRestTemplate.delete("3", IndexCoordinates.of("phone"));
        // 根据查询结果删除
//        NativeSearchQuery nativeSearchQueryBuilder = new NativeSearchQueryBuilder()
//                .withQuery(QueryBuilders.matchQuery("title","小米"))
//                .build();
//        elasticsearchRestTemplate.delete(nativeSearchQueryBuilder,Item.class,IndexCoordinates.of("phone"));

    }

    @Test
    public void search() {
        NativeSearchQuery nativeSearchQueryBuilder = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery("title", "小米"))
                .build();
        SearchHits<Item> search = elasticsearchRestTemplate.search(nativeSearchQueryBuilder, Item.class);
        search.getSearchHits().forEach(System.out::println);
    }

    /**
     * 分页
     */
    @Test
    public void page() {
        NativeSearchQuery nativeSearchQueryBuilder = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.multiMatchQuery("小米OPPO中兴华为", "title"))
                .withPageable(PageRequest.of(0, 3))
                .build();
        SearchHits<Item> search = elasticsearchRestTemplate.search(nativeSearchQueryBuilder, Item.class);
        System.out.println("总条数:"+search.getTotalHits());
        search.getSearchHits().forEach(System.out::println);

    }

    /**
     * 排序
     */
    @Test
    public void order() {
        NativeSearchQuery nativeSearchQueryBuilder = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.multiMatchQuery("小米OPPO中兴华为", "title"))
                .withPageable(PageRequest.of(0, 3))// 分页
                .withSourceFilter(new FetchSourceFilter(new String[]{"id","title","price"},null)) //过滤字段
                .withSort(SortBuilders.fieldSort("price").order(SortOrder.ASC))
                .build();
        SearchHits<Item> search = elasticsearchRestTemplate.search(nativeSearchQueryBuilder, Item.class);
        search.getSearchHits().forEach(System.out::println);

    }

    /**
     * 聚合
     */
    @Test
    public void agg() {
        String aggName = "popBrand";
        NativeSearchQuery nativeSearchQueryBuilder = new NativeSearchQueryBuilder()
//                .withQuery(QueryBuilders.multiMatchQuery("小米OPPO中兴华为", "title"))
//                .withPageable(PageRequest.of(0, 3))
//                .withSort(SortBuilders.fieldSort("price").order(SortOrder.ASC))
                .addAggregation(AggregationBuilders.terms(aggName).field("brand"))
                .build();
        SearchHits<Item> search = elasticsearchRestTemplate.search(nativeSearchQueryBuilder, Item.class);
        search.getSearchHits().forEach(System.out::println);
//        解析聚合
        Aggregations aggregations = search.getAggregations();
        Terms terms = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        buckets.forEach(bucket ->
        {
            System.out.println(bucket.getKey());
            System.out.println(bucket.getDocCount());
        });
    }

}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

just路人周

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值