1. 程式人生 > >Elasticsearch 索引管理

Elasticsearch 索引管理

客戶端

ES 提供多種不同的客戶端:

1.TransportClient

ES提供的傳統客戶端,官方計劃8.0版本刪除此客戶端。

 

2.RestClient

RestClient是官方推薦使用的,它包括兩種:Java Low Level REST Client和 Java High Level REST Client。

ES在6.0之後提供 Java High Level REST Client, 兩種客戶端官方更推薦使用 Java High Level REST Client,不過當前它還處於完善中,有些功能還沒有。

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest‐high‐level‐client</artifactId>
    <version>6.2.1</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>6.2.1</version>
</dependency>

 

 

建立搜尋工程

匯入es 依賴及工具測試依賴

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>6.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>6.2.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>

 

 

yml 配置檔案

server:
  port: 40100
spring:
  application:
    name: xc-service-search

#自定義引數
search:
  elasticsearch:
    hostlist: ${eshostlist:127.0.0.1:9200} #多個結點中間用逗號分隔

 

配置類

我在配置類裡配置了倆個客戶端,分別是  RestHighLevelClient,RestClient

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("${search.elasticsearch.hostlist}")
    private String  hostlist;


//    客戶端    resthighlevelclient  配置
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        String[] hostStrs = hostlist.split(",");
        HttpHost[] httpHostArray = new HttpHost[hostStrs.length];

//        指標
        int i = 0;

        for (String hostStr : hostStrs) {

//            切割  埠       127.0.0.1:9200
            String[] split = hostStr.split(":");   // split[0]      ip     // split[1]  port
            httpHostArray[i++] = new HttpHost(split[0],Integer.parseInt(split[1]) ,"http");
        }

        return new RestHighLevelClient(RestClient.builder(httpHostArray));
    }

    //客戶端  restClient配置
    @Bean
    public RestClient restClient(){
        
        String[] hostStrs = hostlist.split(",");
        HttpHost[] httpHostArray = new HttpHost[hostStrs.length];

//        指標
        int i = 0;

        for (String hostStr : hostStrs) {

//            切割  埠       127.0.0.1:9200
            String[] split = hostStr.split(":");   // split[0]      ip     // split[1]  port
            httpHostArray[i++] = new HttpHost(split[0],Integer.parseInt(split[1]) ,"http");
        }


        return RestClient.builder(httpHostArray).build();
    }
}

 

springboot 啟動類

@SpringBootApplication
public class SearchApplication {

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

 

 

建立索引庫

方法一

建立索引

put http://localhost:9200/索引名稱

{
    "settings":{
        "index":{
            "number_of_shards":1,    #分片的數量
            "number_of_replicas":0    #副本數量
        }
    }
}

建立對映:

put http://localhost:9200/索引庫名稱/型別名稱/_mapping

{
    "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"
            },
          "timestamp": {
            "type": "date",
            "format": "yyyy‐MM‐dd HH:mm:ss||yyyy‐MM‐dd||epoch_millis"
            }
     }
}

 

方法二

 java Client

import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
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.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

@SpringBootTest(classes = SearchApplication.class)
@RunWith(SpringRunner.class)
public class TestES {

    @Resource
    RestHighLevelClient client;

    @Resource
    RestClient restClient;


    @Test
    public void fun01() throws Exception {
        //建立索引請求物件,並設定索引名稱
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("test05");

        //設定索引引數
        createIndexRequest.settings(Settings.builder().put("number_of_shards",1).put("number_of_replicas",0));

        //對映
        createIndexRequest.mapping("doc","{\n" +
                "    \"properties\": {\n" +
                "        \"name\": {\n" +
                "            \"type\": \"text\",\n" +
                "            \"analyzer\":\"ik_max_word\",\n" +
                "            \"search_analyzer\":\"ik_smart\"\n" +
                "            },\n" +
                "        \"description\": {\n" +
                "            \"type\": \"text\",\n" +
                "            \"analyzer\":\"ik_max_word\",\n" +
                "            \"search_analyzer\":\"ik_smart\"\n" +
                "            },\n" +
                "         \"studymodel\": {\n" +
                "            \"type\": \"keyword\"\n" +
                "            },\n" +
                "          \"price\": {\n" +
                "            \"type\": \"float\"\n" +
                "            },\n" +
                "          \"timestamp\": {\n" +
                "            \"type\": \"date\",\n" +
                "            \"format\": \"yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis\"\n" +
                "            }\n" +
                "     }\n" +
                "}", XContentType.JSON);


            //建立索引操作客戶端
        IndicesClient indices = client.indices();

        //建立響應物件
        CreateIndexResponse createIndexResponse = indices.create(createIndexRequest);

        //得到響應結果
        boolean acknowledged = createIndexResponse.isAcknowledged();

        System.out.println(acknowledged);
    }
}

 

刪除索引庫

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.admin.indices.delete.DeleteIndexResponse;
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.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

@SpringBootTest(classes = SearchApplication.class)
@RunWith(SpringRunner.class)
public class TestES {

    @Resource
    RestHighLevelClient client;

    @Resource
    RestClient restClient;

    @Test  //刪除索引庫
    public void delIndex() throws Exception {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("test05");//刪除索引
         DeleteIndexResponse deleteIndexResponse = client.indices().delete(deleteIndexRequest);//刪除索引響應結果
         boolean acknowledged = deleteIndexResponse.isAcknowledged();
         System.out.println(acknowledged);
    }

}

 

新增文件

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.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
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.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@SpringBootTest(classes = SearchApplication.class)
@RunWith(SpringRunner.class)
public class TestES {

    @Resource
    RestHighLevelClient client;

    @Resource
    RestClient restClient;


    @Test
    public void testAddDocument() throws Exception {

        Map<String, Object> jsonMap = new HashMap<String, Object>();

        jsonMap.put("name", "小紅帽");
        jsonMap.put("description","這是小紅帽賣火柴的勵志故事");
        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);

        //索引請求物件
        IndexRequest indexRequest = new IndexRequest("test05","doc");

        //指定索引文件內容
        indexRequest.source(jsonMap);

        //索引響應物件
        IndexResponse indexResponse = client.index(indexRequest);

        DocWriteResponse.Result result = indexResponse.getResult();
        System.out.println(result);
    }
}

 

搜尋文件

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.admin.indices.delete.DeleteIndexResponse;
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.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.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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

@SpringBootTest(classes = SearchApplication.class)
@RunWith(SpringRunner.class)
public class TestES {

    @Resource
    RestHighLevelClient client;

    @Resource
    RestClient restClient;


//    查詢文件
    @Test
    public void testFindDocument() throws IOException {
        GetRequest getRequest = new GetRequest("test05","doc", "zUGVE2gBgTQT4AAg65BL");

        GetResponse getResponse = client.get(getRequest);
        boolean exists = getResponse.isExists();

        Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
        System.out.println(sourceAsMap);
    }
}

 

 

更新文件

ES更新文件的順序是:先檢索到文件、將原來的文件標記為刪除、建立新文件、刪除舊文件,建立新文件就會重建索引。

通過請求Url有兩種方法:

1、完全替換

Post:http://localhost:9200/索引庫/type/id

  {
    
        "key1" : "value1",
        "key2" : "value2"
   }

 

2. 區域性替換 

post: http://localhost:9200/索引庫/type/id/_update

{
    "type":{
        "key1":"value1"
    }
}

 

Java Client

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.admin.indices.delete.DeleteIndexResponse;
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.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
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.elasticsearch.rest.RestStatus;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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

@SpringBootTest(classes = SearchApplication.class)
@RunWith(SpringRunner.class)
public class TestES {

    @Resource
    RestHighLevelClient client;

    @Resource
    RestClient restClient;


    @Test
    public void testUpdate() throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("test05", "doc", "3");

        Map<String,Object> jsonMap = new HashMap<>();
        jsonMap.put("name", "鴨梨牌洗衣機");

        updateRequest.doc(jsonMap);

        UpdateResponse update = client.update(updateRequest);
        RestStatus status = update.status();
        System.out.println(status);
    }



}

 

刪除文件

根據id刪除,格式如下:

DELETE    /{index}/{type}/{id}

 

搜尋匹配刪除,將搜尋出來的記錄刪除,格式如下:
POST        /{index}/{type}/_delete_by_query

搜尋的請求體如下

{
    "query":{
        "term":{
            "name":"鴨梨牌洗衣機"
        }
    }
}

 

java client

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.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
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.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
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.elasticsearch.rest.RestStatus;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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

@SpringBootTest(classes = SearchApplication.class)
@RunWith(SpringRunner.class)
public class TestES {

    @Resource
    RestHighLevelClient client;

    @Resource
    RestClient restClient;

    @Test
    public void testDelDoc() throws IOException {
        //索引請求物件
        DeleteRequest deleteRequest = new DeleteRequest("test05","doc","3");

//        刪除索引請求物件
        DeleteResponse delete = client.delete(deleteRequest);

        //獲取響應結果
        DocWriteResponse.Result result = delete.getResult();

        System.out.println(result);
    }
}