springboot集成elasticsearch8.X(8.11) 最新版的Java API Client 接口
•
Jave
1.官网网址:https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/8.11/getting-started-java.html
2.springboot 的elasticsearch相关依赖
co.elastic.clients
elasticsearch-java
8.11.2
org.elasticsearch.client
elasticsearch-rest-client
org.elasticsearch.client
elasticsearch-rest-client
8.11.2
com.fasterxml.jackson.core
jackson-databind
2.12.3
jakarta.json
jakarta.json-api
2.0.1
org.projectlombok
lombok
3.添加配置文件
@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);
}
}
4.操作数据
4.1 测试的实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
public String userName;
public Integer age;
public String gender;
}
4.2插入数据
我是在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();
}
4.3.查询数据
GetResponse 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");
}
添加match条件查询
User user = new User ();
try {
SearchResponse search = esClient.search(s -> s.
index("bank")
.query(q -> q
.match(t -> t
.field("userName")
.query("测试"))
)
,
User .class);
List<Hit> hits = search.hits().hits();
hits.forEach(productHit -> {
User source = productHit.source();
System.out.println(source.toString());
});
} catch (Exception e) {
e.printStackTrace();
}
删除和修改可以参考官网
官网地址
本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/81a4b057bf.html
