1.官网网址:https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/8.11/getting-started-java.html
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>8.11.2</version>
<exclusions>
<exclusion>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>8.11.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
<!-- Needed only if you use the spring-boot Maven plugin -->
<dependency>
<groupId>jakarta.json</groupId>
<artifactId>jakarta.json-api</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
@Configuration
public class GulimallElasticsearchConfig {
//创造连接,并返回json格式数据
@Bean
public ElasticsearchClient elasticsearchClient(){
RestClient client = RestClient.builder(new HttpHost("localhost",9200,"http")).build();
ElasticsearchTransport transport = new RestClientTransport(client, new JacksonJsonpMapper());
return new ElasticsearchClient(transport);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
public String userName;
public Integer age;
public String gender;
}
我是在controller层测试的,操作数据之前请先注入ElasticsearchClient ,检查注入的包是否正确
?import co.elastic.clients.elasticsearch.ElasticsearchClient;
@Autowired
private ElasticsearchClient esClient;
User user = new User("测试", 18, "男");
try {
esClient.index(i -> i
.id("1")
.index("user")
.document(user));
} catch (IOException e) {
e.printStackTrace();
}
GetResponse<User > response = esClient.get(g -> g
.index("user")
.id("1"),
User.class
);
if (response.found()) {
User user = response.source();
logger.info("user name " + user.getUserName());
} else {
logger.info ("Product not found");
}
User user = new User ();
try {
SearchResponse<User> search = esClient.search(s -> s.
index("bank")
.query(q -> q
.match(t -> t
.field("userName")
.query("测试"))
)
,
User .class);
List<Hit<User>> hits = search.hits().hits();
hits.forEach(productHit -> {
User source = productHit.source();
System.out.println(source.toString());
});
} catch (Exception e) {
e.printStackTrace();
}
删除和修改可以参考官网