SpringBoot整合es7.6.1基本api使用

一、pom.xml引入需要的依赖

<?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 http://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.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zhang</groupId>
    <artifactId>zhang-es-jd</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>zhang-es-jd</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <!--java版本-->
        <java.version>1.8</java.version>
        <!--导入es版本与本地一致-->
        <elasticsearch.version>7.6.1</elasticsearch.version>
    </properties>

    <dependencies>
        <!--解析网页-->
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.10.2</version>
        </dependency>
        <!--thymeleaf模板引擎-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--es -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <!--web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.51</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </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>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

二、es客户端配置

package com.zhang.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;

/**
 * @author zhang
 * @create 2020-12-28 14:55
 */

//spring2步骤:
//1. 找对象
//2.放入spring中
//springboot核心
//xxxAutoConfiguration    xxxProperties

@Configuration
public class ElasticSearchClientConfig {
    //相较xml<bean id="方法名" class="返回值">
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        return new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1", 9200, "http")));
    }
}

三、es操作索引测试

1.es创建索引

//对应的kibana语句
PUT /book
{
  "mappings": {
    "properties": {
      "book_name":{
        "type": "keyword",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_smart"
      },
      "price":{
        "type": "text"
      },
      "imgPath":{
        "type": "keyword"
      }
    }
  }
}
 @Test
 void createIndex() throws IOException {
        //新建创建索引请求指定索引名称
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("book");
        //设置分片和副本
        createIndexRequest.settings(Settings.builder()
                .put("index.number_of_shards", 3)
                .put("index.number_of_replicas", 2)
        );
        //设置字段映射(4种方式这里是一种)
        XContentBuilder builder = XContentFactory.jsonBuilder();
        builder.startObject();
        {
            builder.startObject("properties");
            {
                // es7及以后去掉了映射类型--person
                builder.startObject("book_name");
                {
                    builder.field("type", "text");//name字段为text类型
                    builder.field("analyzer", "ik_max_word");//创建索引时细粒度分词
                    builder.field("search_analyzer","ik_smart");//搜索时粗粒度分词
                }
                builder.endObject();
            }
            {
                builder.startObject("price");
                {
                    builder.field("type", "text");
                }
                builder.endObject();
            }
            {
                builder.startObject("imgPath");
                {
                    builder.field("type", "keyword");
                }
                builder.endObject();
            }
            builder.endObject();
        }
        builder.endObject();
        createIndexRequest.mapping(builder);
        //使用高级客户端执行上面创建的索引请求,返回创建索引相应
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        System.out.println(createIndexRequest.index());
    }

2.判断索引是否存在

//测试判断是否拥有某个索引
    @Test
    void existsIndex() throws IOException {
        //创建获取索引请求
        GetIndexRequest getIndexRequest = new GetIndexRequest("spring_index");
        //执行获取索引请求判断是否有这个索引
        boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

3.获取索引信息

// kibana语句
GET /book
//获取索引信息
    @Test
    void getIndex() throws IOException {
        //创建获取索引请求
        GetIndexRequest getIndexRequest = new GetIndexRequest("book");
        //执行获取索引请求判断是否有这个索引
        GetIndexResponse getIndexResponse = restHighLevelClient.indices().get(getIndexRequest, RequestOptions.DEFAULT);
        System.out.println(getIndexResponse);
    }

4.删除索引

// kibana语句
DELETE /spring_index
//删除索引
    @Test
    void deleteIndex() throws IOException {
        //创建删除索引请求
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("spring_index");
        //执行
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }

四、es操作文档测试

1.添加文档

// kibana语句
	PUT /book/_doc/1
	{
	  "book_name":"Java核心技术 第11版",
	  "price":"231.40",
	  "imgPath":"//img13.360buyimg.com/n1/s200x200_jfs/t1/92329/23/8897/158518/5e09abdcE2cd17eb5/056bbe9e4803be8d.jpg"
	}
 //创建文档
    @Test
    void createDocument() throws IOException {
        //创建对象
       Book user = new Book("Java核心技术 第11版","231.40","//img13.360buyimg.com/n1/s200x200_jfs/t1/92329/23/8897/158518/5e09abdcE2cd17eb5/056bbe9e4803be8d.jpg");
        //创建添加文档的请求
        IndexRequest indexRequest = new IndexRequest("book");
        //设置id 不设置则为es生成默认的
        indexRequest.id("1");
        //放入要索引的文档信息    核心(.source)
        indexRequest.source(JSON.toJSONString(user),XContentType.JSON);
        IndexResponse index = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);

        System.out.println(index.toString());//返回索引信息
        System.out.println(index.status());//返回创建信息
    }

2.查看文档是否存在

//查看是否存在
    @Test
    void existsDocument() throws IOException {
        GetRequest getRequest = new GetRequest("book","1");
        boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
        System.out.println(exists);//查看是否存在
    }

3.查看文档信息

//kibana语句
GET /book/_doc/1
//查看文档信息
    @Test
    void getDocument() throws IOException {
        GetRequest getRequest = new GetRequest("book","1");
        GetResponse documentFields = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        //查看是否存在
        System.out.println(documentFields.isExists());
        //值查询_source中的信息
        System.out.println(documentFields.getSourceAsString());
        //查看返回的所有信息
        System.out.println(documentFields.toString());
        //_source转map
        System.out.println(documentFields.getSource());
    }

4.更新文档信息

//kibana语句
POST /book/_doc/1/_update
{
  "doc":{
    "book_name":"西游记",
    "price":"88",
    "imgPath":"xxxx"
  }
}
 //更新文档信息
    @Test
    void updateDocument() throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("book","1");
        Book book = new Book("西游记", "88", "//img10/xxx.jpg");
        updateRequest.doc(JSON.toJSONString(book),XContentType.JSON);
        UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        //获取更新状态
        System.out.println(update.status());
    }

5.删除文档信息

//kibana语句
DELETE /book/_doc/1

//删除文档信息
    @Test
    void deleteDocument() throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest("book","1");
        DeleteResponse delete = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(delete.status());//删除状态
        System.out.println(delete.toString());//删除信息
    }

6.批量添加文档处理

//批量添加文档处理
    @Test
    void bulkAddDocument() throws IOException {
        //创建请求对象
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");
        ArrayList<Book> books = new ArrayList<>();
        books.add(new Book("西游记", "88", "//img10/xxx.jpg"));
        books.add(new Book("西游记2", "82", "//img11/xxx.jpg"));
        books.add(new Book("西游记3", "81", "//img12/xxx.jpg"));
        books.add(new Book("西游记4", "84", "//img13/xxx.jpg"));
        books.add(new Book("西游记5", "85", "//img14/xxx.jpg"));
        books.add(new Book("西游记6", "89", "//img16/xxx.jpg"));
        for (int i = 0; i < books.size(); i++) {
            bulkRequest.add(
                    new IndexRequest("book")
                            .id((i+1)+"")
                            .source(JSON.toJSONString(books.get(i)),XContentType.JSON)
            );
        }
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulkResponse.hasFailures());//判断是否执行失败  即false为true
    }
//批量删除
    @Test
    void bulkDeleteDocument() throws IOException {
        //创建请求对象indices()
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");
        for (int i = 0; i < 7; i++) {
            bulkRequest.add(
                    new DeleteRequest("book")
                            .id((i+1)+"")
            );
        }
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulkResponse.hasFailures());//判断是否执行失败  即false为true
    }

7.查询文档

//查询
    //SearchRequest 搜索请求
    //SearchSourceBuilder 搜索条件
    //TermQueryBuilder  精确查找
    //MatchAllQueryBuilder 查找全部
    //HighlightBuilder   高亮
    // 。。。。Builder 查询时使用的条件

    @Test
    void searchDocument() throws IOException {
        //创建请求
        SearchRequest searchRequest = new SearchRequest(EsConst.EX_INDEX);
        //构建搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //精确查询
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "wang1");
        //条件查询
        QueryBuilder queryBuilder = QueryBuilders.matchQuery("name","wang1");
        //查询全部
        MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
        //构建搜索
        searchSourceBuilder.query(matchAllQueryBuilder);
        //搜索build放入到查询请求中
        searchRequest.source(searchSourceBuilder);
        //执行
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //查询结果   (GET  /index/type/1 )
        System.out.println(searchResponse.toString());
        //获取某一部分值
        System.out.println(JSON.toJSONString(searchResponse.getHits()));
        //获取存储的数据转为map集合
        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsMap());
        }
    }

总结

api与kibana中的语句格式一致,调用同名方法基本就可以实现操控es了

友情链接: 狂神说java之es7.6.1版本讲解

https://www.bilibili.com/video/BV17a4y1x7zq?p=1.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值