Java操作ElasticSearch8.2.0文档(二)

不知道怎么建索引的请跳转上一篇文章Java操作ElasticSearch8.2.0索引库

ElasticSearch官方文档网站

1.导入maven依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
        </dependency>

        <dependency>
            <groupId>co.elastic.clients</groupId>
            <artifactId>elasticsearch-java</artifactId>
            <version>8.2.0</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.3</version>
        </dependency>

        <dependency>
            <groupId>jakarta.json</groupId>
            <artifactId>jakarta.json-api</artifactId>
            <version>2.0.1</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.12</version>
            <scope>runtime</scope>
        </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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
		<!--FastJson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.71</version>
        </dependency>
		<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
    </dependencies>

2.对ES文档进行操作

2.1 文档增加

官方示例:


Product product = new Product("bk-1", "City bike", 123.0);

IndexResponse response = esClient.index(i -> i
    .index("products")
    .id(product.getSku())
    .document(product)
);

logger.info("Indexed with version " + response.version());

参考

@Test
    void testAddDocument() throws IOException {
    
    
        Hotel hotel = hotelService.getById(36934L);
        HotelDoc hotelDoc = new HotelDoc(hotel);
        elasticsearchClient.index(request -> request
                .index("hotel")
                .id(hotelDoc.getId().toString())
                .document(hotelDoc)
        );
    }

2.2 批量添加

官方示例:


List<Product> products = fetchProducts();

BulkRequest.Builder br = new BulkRequest.Builder();

for (Product product : products) {
    
    
    br.operations(op -> op           
        .index(idx -> idx            
            .index("products")       
            .id(product.getSku())
            .document(product)
        )
    );
}

BulkResponse result = esClient.bulk(br.build());

// Log errors, if any
if (result.errors()) {
    
    
    logger.error("Bulk had errors");
    for (BulkResponseItem item: result.items()) {
    
    
        if (item.error() != null) {
    
    
            logger.error(item.error().reason());
        }
    }
}

举例:

@Test
    void testBulkRequest() throws IOException {
    
    
        List<Hotel> hotels = hotelService.list();
        List<BulkOperation> bulkOperations = new ArrayList<>();
        hotels.forEach(hotel -> {
    
    
            HotelDoc hotelDoc = new HotelDoc(hotel);
            bulkOperations.add(BulkOperation.of(bo -> bo
                    .index(ob -> ob
                            .id(hotelDoc.getId().toString())
                            .document(hotelDoc))));
        });
        elasticsearchClient.bulk(br -> br.index("hotel").operations(bulkOperations));
    }

2.3增删改查批量添加操作

package cn.itcast.hotel;

import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.impl.HotelService;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import co.elastic.clients.elasticsearch.core.GetResponse;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import co.elastic.clients.elasticsearch.indices.CreateIndexRequest;
import co.elastic.clients.elasticsearch.monitoring.BulkRequest;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 尹稳健~
 * @version 1.0
 * @time 2023/5/28
 */
@SpringBootTest
public class HotelDocumentTest {
    
    

    private ElasticsearchClient elasticsearchClient;

    @Autowired
    private HotelService hotelService;


    @Test
    void testAddDocument() throws IOException {
    
    
        Hotel hotel = hotelService.getById(36934L);
        HotelDoc hotelDoc = new HotelDoc(hotel);
        elasticsearchClient.index(request -> request
                .index("hotel")
                .id(hotelDoc.getId().toString())
                .document(hotelDoc)
        );
    }

    @Test
    void testGetDocumentById() throws IOException {
    
    
        GetResponse<HotelDoc> hotelDocGetResponse = elasticsearchClient.get(request -> request
                        .index("hotel")
                        .id("36934"),
                HotelDoc.class
        );
        if (hotelDocGetResponse.found()) {
    
    
            HotelDoc hotelDoc = hotelDocGetResponse.source();
            System.out.println(hotelDoc);
        }
    }

    @Test
    void testUpdateDocument() throws IOException {
    
    
        Hotel hotel = new Hotel();
        hotel.setPrice(332);
        hotel.setStarName("二钻");
        elasticsearchClient.update(request -> request
                        .index("hotel")
                        .id("36934")
                        .doc(
                                hotel
                        ),
                HotelDoc.class
        );
    }

    @Test
    void testDeleteDocument() throws IOException {
    
    
        elasticsearchClient.delete(request -> request
                .index("hotel")
        );
    }

    @Test
    void testBulkRequest() throws IOException {
    
    
        List<Hotel> hotels = hotelService.list();
        List<BulkOperation> bulkOperations = new ArrayList<>();
        hotels.forEach(hotel -> {
    
    
            HotelDoc hotelDoc = new HotelDoc(hotel);
            bulkOperations.add(BulkOperation.of(bo -> bo
                    .index(ob -> ob
                            .id(hotelDoc.getId().toString())
                            .document(hotelDoc))));
        });
        elasticsearchClient.bulk(br -> br.index("hotel").operations(bulkOperations));
    }

    @BeforeEach
    void setUp() {
    
    
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        Credentials creds = new UsernamePasswordCredentials("elastic", "J=9XqTBAk-2GLwd_msUx");
        credentialsProvider.setCredentials(AuthScope.ANY, creds);
        RestClient restClient = RestClient.builder(
                HttpHost.create("http://192.168.33.136:9200")
        ).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
    
    
            @Override
            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
    
    
                return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
        }).build();
        RestClientTransport restClientTransport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        elasticsearchClient = new ElasticsearchClient(restClientTransport);
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_46073538/article/details/130917040
今日推荐