SpringBoot通过Jest整合EasticSearch案例

一、搭建环境

1)、引入相关Jar

<!-- https://mvnrepository.com/artifact/io.searchbox/jest -->
<dependency>
    <groupId>io.searchbox</groupId>
    <artifactId>jest</artifactId>
    <version>5.3.3</version>
</dependency>

2)、配置 EasticSearch访问uri

spring.elasticsearch.jest.uris=http://192.168.43.118:9200/

二、测试是否整合成功

1)、编写一个用于测试的bean,设置id为JestId

public class Article {
    @JestId
    private Integer id;
    private  String author;
    private String title;
    private String content;

    public Integer getId() {
        return id;
    }
...

2)、编写保存索引的单元测试

@Autowired
    JestClient jestClient;

    /**
     * 1、给ES中索引(保存)一个文档
     */
    @Test
    public void addESTest(){
        //封装要保存的内容
        Article article = new Article();
        article.setId(1);
        article.setTitle("Java入门到放弃");
        article.setAuthor("张三");
        article.setContent("Java是蓝领搬砖工!");

        //构建一个索引
        Index index = new Index.Builder(article).index("zhq").type("news").build();
        try {
            //执行保存索引
            jestClient.execute(index);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

浏览器访问看是否保存成功:

2)、编写全文搜索单元测试

    @Autowired
    JestClient jestClient;
    /**
     * 2、全文搜索测试
     */
    @Test
    public void searchESTest(){
        //查询条件表达式
        String json="{\n" +
                "    \"query\" : {\n" +
                "        \"match\" : {\n" +
                "            \"content\" : \"蓝领\"\n" +
                "        }\n" +
                "    }\n" +
                "}";
        //构建查询条件
        Search search = new Search.Builder(json).addIndex("zhq").addType("news").build();
        try {
            //执行查询
            SearchResult result = jestClient.execute(search);
            System.out.println("result:"+result.getJsonString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

查询结果:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值