版本:elasticsearch7.17
参考官方文档:https://www.elastic.co/guide/en/elasticsearch/client/index.html
前言:
在项目中操作es基本都是基于spring或者springboot框架,直接用java操作es的场景比较少,而且相对于框架而言,单纯的用java操作es语法过于复杂,在此,只是简单的做个实例,具体可参考官方文档
引入
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>7.17.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
<scope>compile</scope>
</dependency>
编写实体类
@Data
public class Goods {
private String name;
private String images;
private Integer price;
}
测试类
@Test
public void test01() throws IOException {
RestClient restClient = RestClient.builder(new HttpHost("192.168.233.134" , 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient , new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
SearchResponse<Goods> search = client.search(s -> s
.index("goods")
.query(q -> q
.term(t -> t
.field("name")
.value(v -> v.stringValue("iphone"))
)),
Goods.class);
for (Hit<Goods> hit: search.hits().hits()) {
System.out.println("hit.source() = " + hit.source());
}
}