ElasticSearch  集成springboot api 的使用

ElasticSearch 集成springboot api 的使用

集成springboot

找官网翻资料https://www.elastic.co/guide/en/elasticsearch/client/index.html

第一步 创建springboot项目

第二步 引入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.hzx</groupId>
    <artifactId>elasticsearch-api</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>elasticsearch-api</name>
    <description>Demo project for es</description>

    <properties>
        <java.version>1.8</java.version>
        <elasticsearch.version>7.6.1</elasticsearch.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
<!--        <dependency>-->
<!--            <groupId>org.elasticsearch.client</groupId>-->
<!--            <artifactId>elasticsearch-rest-high-level-client</artifactId>-->
<!--            <version>7.6.1</version>-->
<!--        </dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

第三步 配置ElasticSearchCofing

package com.hzx.elasticsearchapi.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName ElasticSearchConfig
 * @Description TODO
 * @Author hzx456
 * @Date 2020/4/18 21:37
 * @Version 1.0
 */
@Configuration
public class ElasticSearchConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client =new RestHighLevelClient(
                RestClient.builder(
                  new HttpHost("127.0.0.1",9200,"http")
                )
        );
        return client;
    }
}

第四步 测试API

创建索引

@Autowired
@Qualifier("restHighLevelClient")
private RestHighLevelClient client;
//创建索引
@Test
void testCreateIndex() throws Exception {
    //创建请求
    CreateIndexRequest createIndexRequest = new CreateIndexRequest("index_1");
    //使用client 执行请求
    CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
    System.out.println(createIndexResponse);
}

执行测试

控制台没有打印错误,去head看看创建成功了吗

查看索引

//查看所有是否存在
@Test
void testGetIndex() throws Exception{
    //创建请求
    GetIndexRequest index_1 = new GetIndexRequest("index_1");
    //执行
    GetIndexResponse getIndexResponse = client.indices().get(index_1, RequestOptions.DEFAULT);
    System.out.println(getIndexResponse.getMappings());
}

执行test ,控制台打印,

删除索引

//删除索引
@Test
void delIndex() throws Exception{
    //创建请求
    DeleteIndexRequest index_1 = new DeleteIndexRequest("test2");
    //执行
    AcknowledgedResponse delete = client.indices().delete(index_1, RequestOptions.DEFAULT); client.indices().delete(index_1, RequestOptions.DEFAULT);
    System.out.println(delete.isAcknowledged());
}

执行查看

创建文档

先创建user类

package com.hzx.elasticsearchapi.config.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @ClassName User
 * @Description TODO
 * @Author hzx456
 * @Date 2020/4/18 22:33
 * @Version 1.0
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private String name;
    private long age;
    private String[] desc;
}

引入fastjson ,因为 es 面向json的

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.68</version>
</dependency>

测试 创建文档代码

//创建文档
@Test
void createDocument() throws IOException {
    //创建对象
    User user = new User();
    user.setName("lzh");
    user.setAge(18);
    String[] desc={"个性化","技术宅","四眼仔"};
    user.setDesc(desc);

    IndexRequest indexRequest = new IndexRequest("index_1");
    indexRequest.id("1");
    indexRequest.source(JSON.toJSONString(user), XContentType.JSON);
    IndexResponse index = client.index(indexRequest, RequestOptions.DEFAULT);
    System.out.println(index.status());//输出命令执行状态
    System.out.println(index.toString());//返回信息
}

运行测试

查看head

查看文档是否存在

//查看文档是否存在
@Test
void testIsExists() throws IOException {
    GetRequest getRequest = new GetRequest("index_1","1");
  // 不获取返回的 _source 的上下文了
    getRequest.fetchSourceContext(new FetchSourceContext(false));
    boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);

    System.out.println(exists);
}

执行结果

获取文档信息

//获取文档信息
@Test
void testGetDocument() throws IOException {
    GetRequest getRequest = new GetRequest("index_1","1");
    GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);

    System.out.println(documentFields.getSource());//获取上下文
    System.out.println(documentFields.getSourceAsString());//返回字符串类型的结果
    System.out.println(documentFields.getVersion());//返回文档版本信息
    System.out.println(documentFields.getSourceAsMap());//返回文档以Map形式
    //……
}

可以获取到很多信息

修改文档

//修改文档
@Test
void testUpdatedDocument() throws IOException {
    UpdateRequest updateRequest = new UpdateRequest("index_1","1");
// 创建对象
    User user = new User();
    user.setName("lzh");
    user.setAge(20);
    String[] desc={"个性化","技术宅","帅气男孩"};
    user.setDesc(desc);
    updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
    UpdateResponse update = client.update(updateRequest, RequestOptions.DEFAULT);
    System.out.println(update.status());

}

执行结果

查看head上改了?

OK(#.#)

删除文档

    //删除文档
    @Test
    void  testDelDocument()throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest("index_1","1");
//        deleteRequest.timeout("10");//访问超时时间
        DeleteResponse delete = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(delete.status());
    }

执行结果

查看head

批量插入

//批量插入
@Test
void  testCreateDocuments()throws IOException {
    List<User> users=new ArrayList<>();
    BulkRequest bulkRequest=new BulkRequest();
    String [] desc={"帅气"};
    users.add(new User("zhangsan",18,desc));
    users.add(new User("zhangsan1",19,desc));
    users.add(new User("zhangsan2",20,desc));
    users.add(new User("zhangsan3",12,desc));
    for (int i=0 ;i<users.size();i++){
        bulkRequest.add(new IndexRequest("index_1").id((i+1)+"")
                .source(JSON.toJSONString(users.get(i)),XContentType.JSON));
    }

    BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
    System.out.println(bulk.status());

}

执行结果

head中的结果

查询多条

//查询
// SearchRequest 搜索请求
// SearchSourceBuilder 条件构造
// HighlightBuilder 构建高亮
// TermQueryBuilder 精确查询
// MatchAllQueryBuilder
// xxx QueryBuilder 对应我们刚才看到的命令!

@Test
void  testSearchDocuments()throws IOException {

    SearchRequest searchRequest=new SearchRequest("index_1");
    //构建搜索条件
    SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();
    sourceBuilder.highlighter();
    // 查询条件,我们可以使用 QueryBuilders 工具来实现
    // QueryBuilders.termQuery 精确
    // QueryBuilders.matchAllQuery() 匹配所有
    // MatchAllQueryBuilder matchAllQueryBuilder =QueryBuilders.matchAllQuery();
    sourceBuilder.query(QueryBuilders.matchAllQuery());
    searchRequest.source(sourceBuilder);
    SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
    search.getHits().forEach(System.out::println);
}

执行结果

本文所有内容从https://www.bilibili.com/video/BV17a4y1x7zq 中吸取