栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

SpringBoot整合ElasticSearch7.16.3

SpringBoot整合ElasticSearch7.16.3

SpringBoot整合ElasticSearch7.16.3

ElasticSearch7.15.x版本后,废弃了高级Rest客户端的功能,转为JavaAPI客户端,以下来源ElasticSearch官网

The Elasticsearch Java API Client is an entirely new client library that has no relation to the older High Level Rest Client (HLRC). This was a deliberate choice to provide a library that is independent from the Elasticsearch server code and that provides a very consistent and easier to use API for all Elasticsearch features.
From https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/migrate-hlrc.html

maven引入
		
            co.elastic.clients
            elasticsearch-java
            7.16.3
        
        
            com.fasterxml.jackson.core
            jackson-databind
            2.12.3
        
        
            jakarta.json
            jakarta.json-api
            2.0.1
        
简单API
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;


@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {
    private String name;

    private String price;

    private String imgPath;
}
配置
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


 @Configuration
public class ElasticSearchConfig {

    @Bean
    public ElasticsearchClient elasticsearchClient() {
    	//对应ElasticSearch的IP端口
        RestClient restClient = RestClient.builder(new HttpHost("xx.xx.xx.xx",9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        return new ElasticsearchClient(transport);
    }
}
索引
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.mapping.KeywordProperty;
import co.elastic.clients.elasticsearch._types.mapping.Property;
import co.elastic.clients.elasticsearch._types.mapping.TextProperty;
import co.elastic.clients.elasticsearch._types.mapping.TypeMapping;
import co.elastic.clients.elasticsearch.indices.*;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

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

@SpringBootTest
class ElasticsearchDemoApplicationTests {

    @Resource
    private ElasticsearchClient elasticsearchClient;

    //对应的kibana语句
    
    // 创建索引
    @Test
    void createIndex() throws IOException {

        // 配置索引
        Map property = new HashMap<>();
        
        property.put("name", new Property(new TextProperty.Builder().analyzer("ik_max_word").searchAnalyzer("ik_smart").index(true).store(true).build()));
        property.put("price", new Property(new KeywordProperty.Builder().index(true).store(true).build()));
        property.put("imgPath", new Property(new KeywordProperty.Builder().index(true).store(true).build()));

        TypeMapping typeMapping = new TypeMapping.Builder().properties(property).build();

        
        IndexSettings indexSettings = new IndexSettings.Builder().numberOfReplicas("5").build();

        CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder()
                .index("book")
                .aliases("b1", new Alias.Builder().isWriteIndex(true).build())
                .mappings(typeMapping)
                .settings(indexSettings)
                .build();

        CreateIndexResponse createIndexResponse = elasticsearchClient.indices().create(createIndexRequest);
        System.out.println(createIndexResponse.acknowledged());
    }

    //测试判断是否拥有某个索引
    @Test
    void existsIndex() throws IOException {
        //创建获取索引请求
        ExistsRequest existsRequest = new ExistsRequest.Builder().index("b2").build();
        //执行获取索引请求判断是否有这个索引
        BooleanResponse booleanResponse = elasticsearchClient.indices().exists(existsRequest);
        System.out.println(booleanResponse.value());
    }

    //获取索引信息
    @Test
    void getIndex() throws IOException {
        //创建获取索引请求
        GetIndexRequest getIndexRequest = new GetIndexRequest.Builder().index("book").build();
        //执行获取索引请求判断是否有这个索引
        GetIndexResponse getIndexResponse = elasticsearchClient.indices().get(getIndexRequest);
        System.out.println(getIndexResponse.result());
    }

    //DELETe /book
    // 删除索引
    @Test
    void deleteIndex() throws IOException {
        //创建删除索引请求
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest.Builder().index("book").build();
        //执行
        DeleteIndexResponse deleteIndexResponse = elasticsearchClient.indices().delete(deleteIndexRequest);
        System.out.println(deleteIndexResponse.acknowledged());
    }

}
文档
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.ye.elasticsearchdemo.pojo.Book;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;


@SpringBootTest
public class DocTests {

    @Resource
    private ElasticsearchClient elasticsearchClient;

    // kibana语句
    
    //创建文档
    @Test
    void createdocument() throws IOException {
        // 创建对象
        Book book = new Book("高性能Mysql", "81.32", "https://img30.360buyimg.com/vc/jfs/t24145/294/1264419103/700620/6d764088/5b580f1eN305e28c1.jpg");
        // 创建添加文档的请求
        IndexRequest indexRequest = new IndexRequest.Builder().index("book").document(book).id("1").build();

        // 执行
        IndexResponse indexResponse = elasticsearchClient.index(indexRequest);

        System.out.println(indexResponse.toString());//返回索引信息
        System.out.println(indexResponse.result());//返回id
    }

    //查看是否存在
    @Test
    void existsdocument() throws IOException {
        GetRequest getRequest = new GetRequest.Builder().index("book").id("1").build();
        GetResponse bookGetResponse = elasticsearchClient.get(getRequest, Book.class);
        //查看是否存在
        System.out.println(bookGetResponse.found());
    }


    //DELETE /book/_doc/1
    //删除文档信息
    @Test
    void deletedocument() throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest.Builder().index("book").id("1").build();
        DeleteResponse delete = elasticsearchClient.delete(deleteRequest);
        System.out.println(delete.result());//删除状态
        System.out.println(delete.toString());//删除信息
    }

    
    @Test
    void getdocument() throws IOException {
        // get /index/_doc/1
        GetRequest getRequest = new GetRequest.Builder().index("book").id("1").build();
        GetResponse bookGetResponse = elasticsearchClient.get(getRequest, Book.class);

        Book book = bookGetResponse.source();
        System.out.println("book = " + book);
    }

    
    @Test
    void getdocumentByPage() throws IOException {
        SearchRequest searchRequest = new SearchRequest.Builder().index("book").from(0).size(10).build();
        SearchResponse bookSearchResponse = elasticsearchClient.search(searchRequest, Book.class);

        List> bookList = bookSearchResponse.hits().hits();
        bookList.forEach(item->System.out.println(item.source()));
    }

	
    @Test
    void updatedocument() throws IOException {
        Book book = new Book();
        book.setName("算法指南");

        UpdateRequest bookBookUpdateRequest = new UpdateRequest.Builder().index("book").id("1").doc(book).build();

        UpdateResponse personUpdateResponse = elasticsearchClient.update(bookBookUpdateRequest, Book.class);

        // 执行结果
        System.out.println(personUpdateResponse.result());
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/758380.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号