springboot整合es客戶端操作elasticsearch(二)


在上章節中整合elasticsearch客戶端出現版本問題進行了處理,這章來進行springboot整合得操作

環境:elaticsearch6.2.1,springboot 2.1.8 客戶端版本采用6.6.1

一 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 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.1.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.cxy</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>elasticsearch</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.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>6.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>6.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </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>
            </plugin>
        </plugins>
    </build>

</project>

二  啟動配置和yml文件

server:
  port: ${port:8085}
spring:
  application:
    name: xc-search-service
  elasticsearch:
    hostlist: ${eshostlist:127.0.0.1:9200}
package com.cxy.elasticsearch.config;

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

@Configuration
public class ElasticsearchConfig {

    @Value("${spring.elasticsearch.hostlist}")
    private String hostlist;

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        //解析hostlist配置信息
        String[] split = hostlist.split(",");
        //創建HttpHost數組,其中存放es主機和端口的配置信息
        HttpHost[] httpHostArray = new HttpHost[split.length];
        for(int i=0;i<split.length;i++){
            String item = split[i];
            httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");
        }
        //創建RestHighLevelClient客戶端
        return new RestHighLevelClient(RestClient.builder(httpHostArray));
    }

    //項目主要使用RestHighLevelClient,對於低級的客戶端暫時不用
    @Bean
    public RestClient restClient(){
        //解析hostlist配置信息
        String[] split = hostlist.split(",");
        //創建HttpHost數組,其中存放es主機和端口的配置信息
        HttpHost[] httpHostArray = new HttpHost[split.length];
        for(int i=0;i<split.length;i++){
            String item = split[i];
            httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");
        }
        return RestClient.builder(httpHostArray).build();
    }

}
package com.cxy.elasticsearch;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages={"com.cxy.elasticsearch"})//掃描本項目下的所有類
public class ElasticsearchApplication {

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

}

注:

@ComponentScan(basePackages={"com.cxy.elasticsearch"})//掃描本項目下的所有類

是可以不加得,只要目錄保持在相關下就可以了

三 controller文件:

package com.cxy.elasticsearch.controller;

import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class EsController {
    @Autowired
    RestHighLevelClient client;

    @Autowired
    RestClient restClient;
    @RequestMapping(value = "/createIndex" ,method = RequestMethod.POST)
    public String createIndex(){
        //創建索引請求對象
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("chenxuyou3");
        // 設置參數
        createIndexRequest.settings(Settings.builder().put("number_of_shards","1").put("number_of_replicas","0"));
        //指定映射
        createIndexRequest.mapping("doc"," {\n" +
                " \t\"properties\": {\n" +
                "            \"studymodel\":{\n" +
                "             \"type\":\"keyword\"\n" +
                "           },\n" +
                "            \"name\":{\n" +
                "             \"type\":\"keyword\"\n" +
                "           },\n" +
                "           \"description\": {\n" +
                "              \"type\": \"text\",\n" +
                "              \"analyzer\":\"ik_max_word\",\n" +
                "              \"search_analyzer\":\"ik_smart\"\n" +
                "           },\n" +
                "           \"pic\":{\n" +
                "             \"type\":\"text\",\n" +
                "             \"index\":false\n" +
                "           }\n" +
                " \t}\n" +
                "}", XContentType.JSON);
        //指定索引操作的客戶端
        IndicesClient indices = client.indices();
        //執行創建索引庫
        CreateIndexResponse createIndexResponse = null;
        try {
            createIndexResponse = indices.create(createIndexRequest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        boolean acknowledged = createIndexResponse.isAcknowledged();
        //獲取返回結果
        System.err.println(acknowledged);
        return "ok";
    }
    @RequestMapping(value = "/deleteIndex",method = RequestMethod.POST)
    public String deleteIndex(){
        DeleteIndexRequest chenxuyou3 = new DeleteIndexRequest("chenxuyou2");
        IndicesClient indices = client.indices();
        AcknowledgedResponse delete =null;
        try {
            delete = indices.delete(chenxuyou3);
        } catch (IOException e) {
            e.printStackTrace();
        }
        boolean acknowledged = delete.isAcknowledged();
        System.err.println(acknowledged);
        return "";
    }
    @RequestMapping(value = "/addDoc",method = RequestMethod.POST)
    public String addDoc(){
//文檔內容
        //准備json數據
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("name", "spring cloud實戰");
        jsonMap.put("description", "本課程主要從四個章節進行講解: 1.微服務架構入門 2.spring cloud 基礎入門 3.實戰Spring Boot 4.注冊中心eureka。");
        jsonMap.put("studymodel", "201001");
        SimpleDateFormat dateFormat =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        jsonMap.put("timestamp", dateFormat.format(new Date()));
        jsonMap.put("price", 5.6f);

        //創建索引創建對象
        //帶有type的方法已經廢棄
       // IndexRequest indexRequest = new IndexRequest("chenxuyou3","doc");
        IndexRequest indexRequest = new IndexRequest("chenxuyou3");
        //文檔內容
        indexRequest.source(jsonMap);
        //通過client進行http的請求
        IndexResponse indexResponse = null;
        try {
            indexResponse = client.index(indexRequest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        DocWriteResponse.Result result = indexResponse.getResult();
        System.err.println(result);
        return "ok";
    }
    @RequestMapping(value = "/selectDoc",method = RequestMethod.GET)
    public String selectDoc(){
        //查詢請求對象
       // GetRequest getRequest = new GetRequest("chenxuyou2","doc","8tyV-m4B7rvW_ZY4LvVU");
        GetRequest getRequest = new GetRequest("chenxuyou3","doc","8tyV-m4B7rvW_ZY4LvVU");
        GetResponse getResponse = null;
        try {
            getResponse = client.get(getRequest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //得到文檔的內容
        Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
        System.out.println(sourceAsMap);
        return "ok" ;
    }


}

 

注:
   //指定映射
        createIndexRequest.mapping("doc"," {\n" +
                " \t\"properties\": {\n" +
                "            \"studymodel\":{\n" +
                "             \"type\":\"keyword\"\n" +
                "           },\n" +
                "            \"name\":{\n" +
                "             \"type\":\"keyword\"\n" +
                "           },\n" +
                "           \"description\": {\n" +
                "              \"type\": \"text\",\n" +
                "              \"analyzer\":\"ik_max_word\",\n" +
                "              \"search_analyzer\":\"ik_smart\"\n" +
                "           },\n" +
                "           \"pic\":{\n" +
                "             \"type\":\"text\",\n" +
                "             \"index\":false\n" +
                "           }\n" +
                " \t}\n" +
                "}", XContentType.JSON);

這個就是我們平時在postman中配置得json文件

例如:

{
    "properties": {
        "description": {
            "type": "text",
            "analyzer": "ik_max_word",
            "search_analyzer": "ik_smart"
        },
        "name": {
            "type": "text",
            "analyzer": "ik_max_word",
            "search_analyzer": "ik_smart"
        },
        "pic": {
            "type": "text",
            "index": false
        },
        "price": {
            "type": "float"
        },
        "studymodel": {
            "type": "keyword"
        },
        "timestamp": {
            "type": "date",
            "format": "yyyy‐MM‐dd HH:mm:ss||yyyy‐MM‐dd||epoch_millis"
        }
    }
}

然后idea會進行編譯下,所以導致閱讀起來不是很好

調用刪除aip接口:

 

 

這個錯誤就是index不存在得意思。所以需要先調用下生成得,再進行刪除

 localhost:8085/createIndex

{
    "timestamp": "2019-12-15T07:10:34.015+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "Elasticsearch exception [type=resource_already_exists_exception, reason=index [chenxuyou3/sefNCOu1T8a7CKW463M83g] already exists]",
    "path": "/createIndex"
}

可以知道這個是存在得意思,隨意修改代碼再重新操作:

調用localhost:8085/addDoc

{
    "timestamp": "2019-12-15T07:13:38.902+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "Validation Failed: 1: type is missing;",
    "path": "/addDoc"
}

缺少type,由於在6版本中並沒有刪除所以需要修改這個部分代碼

  //創建索引創建對象
        //帶有type的方法已經廢棄
        IndexRequest indexRequest = new IndexRequest("chenxuyou3","doc");
       // IndexRequest indexRequest = new IndexRequest("chenxuyou3");
        //文檔內容

如圖中,將type重新加入,就不會報錯了

調用查詢錯誤碼405.請求方式有問題

 

 修改方式再調用

控制台打印null

但是庫里面確實有數據

 

 id有問題,所以每次插入新數據時候id都不會一樣,所以修改id

{price=5.6, studymodel=201001, name=spring cloud實戰, description=本課程主要從四個章節進行講解: 1.微服務架構入門 2.spring cloud 基礎入門 3.實戰Spring Boot 4.注冊中心eureka。, timestamp=2019-12-15 15:15:29}

 

控制台打印出來數據。

所以這邊對索引得刪除與創建,文檔得建立,和數據得查詢已經完成。

下章進行文檔得查詢,修改,映射得修改查詢


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM