前言
提示:这里可以添加本文要记录的大概内容:
本文内容来自于官网。
提示:以下是本篇文章正文内容,下面案例可供参考
一、使用步骤
1.引入库
代码如下(示例):
注意修改 <jakarta-json.version>2.0.1</jakarta-json.version>
<?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.7.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.panbl</groupId>
<artifactId>springboot-es</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-es</name>
<description>springboot-es</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>2021.0.3-SNAPSHOT</spring-cloud.version>
<elasticsearch.version>7.17.0</elasticsearch.version>
<jakarta-json.version>2.0.1</jakarta-json.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>7.17.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.设置配置文件
代码如下(EsConfig ):
package com.panbl.springbootes.config;
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;
/**
* @author PanBangLin
* @version 1.0
* @date 2022/6/18 16:30
*/
@Configuration
public class EsConfig {
@Bean
public ElasticsearchClient esClient(){
// 创建ES客户端部分
RestClient restClient = RestClient.builder(
new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());
return new ElasticsearchClient(transport);
}
}
二、开始使用
1.新建测试类
package com.panbl.springbootes;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch._types.query_dsl.RangeQuery;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.BulkResponseItem;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.TotalHits;
import co.elastic.clients.elasticsearch.core.search.TotalHitsRelation;
import co.elastic.clients.json.JsonData;
import lombok.Data;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
@SpringBootTest
class SpringbootEsApplicationTests {
@Autowired
ElasticsearchClient client;
/**
* 新建索引
*/
@Test
public void insert() throws IOException {
Product product = new Product("bk-1", "City bike", 123.0);
client.index(i -> i
.index("products").id(product.getSku()).document(product));
// 使用静态调用的方法
product.setName("City bike static");
IndexRequest<Object> request = IndexRequest.of(i -> i
.index("products") .id(product.getSku()).document(product));
IndexResponse response = client.index(request);
}
/**
* 批量操作
*/
@Test
public void buik() throws IOException {
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 = client.bulk(br.build());
if (result.errors()) {
System.out.println("Bulk had errors");
for (BulkResponseItem item: result.items()) {
if (item.error() != null) {
System.out.println(item.error().reason());
}
}
}
}
private List<Product> fetchProducts() {
List<Product> list = new ArrayList<Product>();
for (int i= 0 ; i<3 ;i++){
Product product = new Product("bk-" + i + 100, "p" + i, 123.44 + i);
list.add(product);
}
return list;
}
/**
* 通过id查询
*/
@Test
public void readingByID() throws IOException {
GetResponse<Product> response = client.get(g -> g
.index("products")
.id("bk-1"),
Product.class
);
if (response.found()) {
Product product = response.source();
System.out.println("Product name " + product.getName());
} else {
System.out.println ("Product not found");
}
}
/**
* 查询
*/
@Test
public void search() throws IOException {
String searchText = "p0";
SearchResponse<Product> response = client.search(s -> s
.index("products")
.query(q -> q
.match(t -> t
.field("name")
.query(FieldValue.of(searchText))
)
),
Product.class
);
TotalHits total = response.hits().total();
boolean isExactResult = total.relation() == TotalHitsRelation.Eq;
if (isExactResult) {
System.out.println("There are " + total.value() + " results");
} else {
System.out.println("There are more than " + total.value() + " results");
}
List<Hit<Product>> hits = response.hits().hits();
for (Hit<Product> hit: hits) {
Product product = hit.source();
System.out.println(product);
System.out.println("Found product " + product.getSku() + ", score " + hit.score());
}
}
/**
* 嵌套查询
*/
@Test
public void nestedSearch() throws IOException {
String searchText = "bike";
double maxPrice = 10.0;
// Search by product name
Query byName = MatchQuery.of(m -> m
.field("name")
.query(FieldValue.of(searchText))
)._toQuery();
// Search by max price
Query byMaxPrice = RangeQuery.of(r -> r
.field("price")
.gte(JsonData.of(maxPrice))
)._toQuery();
// Combine name and price queries to search the product index
SearchResponse<Product> response = client.search(s -> s
.index("products")
.query(q -> q
.bool(b -> b
.must(byName)
.must(byMaxPrice)
)
),
Product.class
);
TotalHits total = response.hits().total();
boolean isExactResult = total.relation() == TotalHitsRelation.Eq;
if (isExactResult) {
System.out.println("There are " + total.value() + " results");
} else {
System.out.println("There are more than " + total.value() + " results");
}
List<Hit<Product>> hits = response.hits().hits();
for (Hit<Product> hit: hits) {
Product product = hit.source();
System.out.println("Found product " + product.getSku() + ", score " + hit.score());
}
}
}
/**
* 实体类
*/
@Data
class Product {
private String sku;
private String name;
private double price;
public Product(){}
public Product(String sku, String name, double price) {
this.sku = sku;
this.name = name;
this.price = price;
}
}
总结
提示:这里对文章进行总结:
以上就是基于Java Client操作es的内容