学无先后,达者为师

网站首页 编程语言 正文

Spring Boot整合ElasticSearch

作者:RongYu__ 更新时间: 2022-08-28 编程语言

一、ES客户端

ES提供多种不同的客户端:

1、TransportClient

ES提供的传统客户端,官方计划8.0版本删除此客户端。

2、RestClient

RestClient是官方推荐使用的,它包括两种:REST Low Level Client和 REST High Level Client。ES在6.0之后提供REST High Level Client, 两种客户端官方更推荐使用 REST High Level Client,不过当前它还处于完善中,有些功能还没有。

二、搭建工程

2.1.pom.xml

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
</parent>

  <!-- 修改elasticsearch的版本 -->
    <properties>
        <elasticsearch.version>6.2.3</elasticsearch.version>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
    </dependencies>

2.2.application.yml

spring:
  elasticsearch:
    rest:
      uris:
        - http://192.168.113.135:9200

2.3.app

@SpringBootApplication
public class ElasticsearchApp {

	public static void main(String[] args) {
		SpringApplication.run(ElasticsearchApp.class, args);
	}
}

三、索引管理    

3.1 api

创建索引库:

PUT /java06 {  "settings":{     
  "number_of_shards" : 2,    
  "number_of_replicas" : 0 } }

创建映射:

POST /java06/course/_mapping
{
  "_source": {
    "excludes":["description"]
  }, 
    "properties": {
      "name": {
          "type": "text",
          "analyzer":"ik_max_word",
          "search_analyzer":"ik_smart"
      },
      "description": {
          "type": "text",
          "analyzer":"ik_max_word",
          "search_analyzer":"ik_smart"
       },
       "studymodel": {
          "type": "keyword"
       },
       "price": {
          "type": "float"
       },
       "pic":{
           "type":"text",
           "index":false
        }
  }
}

3.1.2.Java Client

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {ElasticsearchApp.class})
public class IndexWriterTest {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
​
   //创建索引库
    @Test
    public void testCreateIndex() throws IOException {
        //创建“创建索引请求”对象,并设置索引名称
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("java06");
        //设置索引参数
        createIndexRequest.settings("{\n" +
                "       \"number_of_shards\" : 2,\n" +
                "       \"number_of_replicas\" : 0\n" +
                "  }", XContentType.JSON);
        createIndexRequest.mapping("course", "{\r\n" + 
                "  \"_source\": {\r\n" + 
                "    \"excludes\":[\"description\"]\r\n" + 
                "  }, \r\n" + 
                "   \"properties\": {\r\n" + 
                "           \"name\": {\r\n" + 
                "              \"type\": \"text\",\r\n" + 
                "              \"analyzer\":\"ik_max_word\",\r\n" + 
                "              \"search_analyzer\":\"ik_smart\"\r\n" + 
                "           },\r\n" + 
                "           \"description\": {\r\n" + 
                "              \"type\": \"text\",\r\n" + 
                "              \"analyzer\":\"ik_max_word\",\r\n" + 
                "              \"search_analyzer\":\"ik_smart\"\r\n" + 
                "           },\r\n" + 
                "           \"studymodel\": {\r\n" + 
                "              \"type\": \"keyword\"\r\n" + 
                "           },\r\n" + 
                "           \"price\": {\r\n" + 
                "              \"type\": \"float\"\r\n" + 
                "           },\r\n" + 
                "  }\r\n" + 
                "}", XContentType.JSON);
        //创建索引操作客户端
        IndicesClient indices = restHighLevelClient.indices();
​
        //创建响应对象
        CreateIndexResponse createIndexResponse = 
            indices.create(createIndexRequest);
        //得到响应结果
        boolean acknowledged = createIndexResponse.isAcknowledged();
        System.out.println(acknowledged);
    } 
  }

3.2.删除索引库

3.2.1.api

DELETE /java06

3.2.2.java client

 //删除索引库
    @Test
    public void testDeleteIndex() throws IOException {
        //创建“删除索引请求”对象
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("java06");
        //创建索引操作客户端
        IndicesClient indices = restHighLevelClient.indices();
        //创建响应对象
        DeleteIndexResponse deleteIndexResponse = 
            indices.delete(deleteIndexRequest);
        //得到响应结果
        boolean acknowledged = deleteIndexResponse.isAcknowledged();
        System.out.println(acknowledged);
    }

3.3.添加文档

3.3.1.api

POST /java06/course/1
{
 "name":"spring cloud实战",
 "description":"本课程主要从四个章节进行讲解: 1.微服务架构入门 2.spring cloud 基础入门 3.实战Spring Boot 4.注册中心eureka。",
 "studymodel":"201001",
 "price":5.6
}

3.3.2.java client

  //添加文档
    @Test
    public void testAddDocument() throws IOException {
        //创建“索引请求”对象:索引当动词
        IndexRequest indexRequest = new IndexRequest("java06", "course", "1");
        indexRequest.source("{\n" +
                " \"name\":\"spring cloud实战\",\n" +
                " \"descriptio
                            n\":\"本课程主要从四个章节进行讲解: 1.微服务架构入门 " +
                "2.spring cloud 基础入门 3.实战Spring Boot 4.注册中心nacos。\",\n" +
                " \"studymodel\":\"201001\",\n" +
                " \"price\":5.6\n" +
                "}", XContentType.JSON);
        IndexResponse indexResponse = 
            restHighLevelClient.index(indexRequest);
        System.out.println(indexResponse.toString());
    }

3.4.批量添加文档

支持在一次API调用中,对不同的索引进行操作。支持四种类型的操作:index、create、update、delete。

  • 语法:

3.4.1

POST /_bulk
{ action: { metadata }} 
{ requestbody }\n
{ action: { metadata }} 
{ requestbody }\n
...

.api

POST /_bulk
{"index":{"_index":"java06","_type":"course"}}
{"name":"php实战","description":"php谁都不服","studymodel":"201001","price":"5.6"}
{"index":{"_index":"java06","_type":"course"}}
{"name":"net实战","description":"net从入门到放弃","studymodel":"201001","price":"7.6"}

3.4.2.java client

@Test
public void testBulkAddDocument() throws IOException {
    BulkRequest bulkRequest = new BulkRequest();
    bulkRequest.add(new IndexRequest("java06", "course").source("{...}",
                                                                  XContentType.JSON));
    bulkRequest.add(new IndexRequest("java06", "course").source("{...}",
                                                                  XContentType.JSON));
    BulkResponse bulkResponse = 
                   restHighLevelClient.bulk(bulkRequest);
    System.out.println(bulkResponse.hasFailures());
}

3.5.修改文档

3.5.1.api

PUT /java06/course/1
{
 "price":66.6
}

3.5.2.java client

//更新文档
@Test
public void testUpdateDocument() throws IOException {
    UpdateRequest updateRequest = new UpdateRequest("java06", "course", "1");
    updateRequest.doc("{\n" +
            "  \"price\":7.6\n" +
            "}", XContentType.JSON);
    UpdateResponse updateResponse = 
                   restHighLevelClient.update(updateRequest);
    System.out.println(updateResponse.getResult());
}

3.6.删除文档

3.6.1.api

DELETE /java06/coures/1

3.6.2.java client

  //根据id删除文档
    @Test
    public void testDelDocument() throws IOException {
        //删除请求对象
        DeleteRequest deleteRequest = new DeleteRequest("java06","course","1");
        //响应对象
        DeleteResponse deleteResponse = 
            restHighLevelClient.delete(deleteRequest);
        System.out.println(deleteResponse.getResult());
    }

四.文档搜索

原文链接:https://blog.csdn.net/RongYu__/article/details/126555441

栏目分类
最近更新