SpringBoot检索篇Ⅳ --- 整合ElasticSearch

知识储备: 

关于ElasticSearch的基本使用我已经在上一篇文章介绍过了(传送门),本篇文章主要讲述的是SpringBoot与ElasticSearch的整合使用。

SpringBoot与ElasticSearch的整合

Springboot默认支持两种技术与ES交互:

1.Jest

1.1 Jest默认不生效,需要导入Jest的工具包:

<dependency>
      <groupId>io.searchbox</groupId>
      <artifactId>jest</artifactId>
      <version>5.3.3</version>
 </dependency>

1.2 默认连接的主机地址是localhost,若不是部署在本地的话需要配置主机地址

spring.elasticsearch.jest.uris=http://172.**.**.**:9200

1.3 创建需要操作的实体类

public class People {
    @JestId //注意要给id加上注解
    private Integer id;
    private String name;
    private Integer age;
    private String gender;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "People{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                '}';
    }
}

1.4  测试:给ES中的索引保存一个文档

   @Autowired
    JestClient jestClient; //SpringBoot已经给我们自动配置好了,可以直接引用
    @Test
    public void contextLoads() {
        //1,给ES中的索引保存一个文档
        People people = new People();
        people.setId(1);
        people.setAge(22);
        people.setGender("男");
        people.setName("王鑫");

        //构建一个索引功能
        Index index = new Index.Builder(people).index("school").type("qinghua").build();
        try {
            jestClient.execute(index);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

1.5 测试:构建搜索功能

 @Test
    public void search(){
        //查询表达式
        String json = "{\n" +
                "    \"query\" : {\n" +
                "        \"match\" : {\n" +
                "            \"name\" : \"王\"\n" +
                "        }\n" +
                "    }\n" +
                "}";
        //构建搜索功能
        Search search = new Search.Builder(json).addIndex("school").addType("qinghua").build();
        try {
            SearchResult result = jestClient.execute(search);
            System.out.println(result.getJsonString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

这里只是给出几个简单的演示,更多的可以详细参考Jest的官方文档

猜你喜欢

转载自www.cnblogs.com/wangxiayun/p/10271122.html