- 环境准备
- Springboot 基本环境
- 自行前往https://start.spring.io/ 构建一个即可
- Elasticsearch服务端
- 简单说下windows版本的安装 https://www.elastic.co/cn/downloads/elasticsearch 下载最新版8.1.0,之后解压 不要放到中文目录下,进入bin目录双击运行elasticsearch.bat.
- Springboot 基本环境
- 相关依赖
-
pom.xml ELasticsearch相关的依赖
<dependency> <groupId>co.elastic.clients</groupId> <artifactId>elasticsearch-java</artifactId> <version>8.1.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.2</version> </dependency>
- application.yml
elasticsearch: host: 127.0.0.1 port: 9200
-
具体实现
首先要建立连接,这样就能在后续使用springboot自动装配
@Autowired
private ElasticsearchClient elasticsearchClient;
具体代码如下
查看代码
package cn.daimao.TestTryProject.bean;
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.elasticsearch.client.RestClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class ElasticClient {
@Value("${elasticsearch.host}")
private String host;
@Value("${elasticsearch.port}")
private Integer port;
@Bean
public ElasticsearchClient getClient() {
RestClientBuilder builder = RestClient.builder(
new HttpHost(host, port));
ElasticsearchTransport transport = new RestClientTransport(builder.build(), new JacksonJsonpMapper());
return new ElasticsearchClient(transport);
}
}
@Autowired
private ElasticsearchClient elasticsearchClient;
@PostMapping("/createIndex")
public ResultJson createIndex(@RequestParam String indexName) throws IOException {
elasticsearchClient.indices().create(createIndex -> createIndex.index(indexName));
return ResultJson.success();
}
上传文档(数据)到索引
.index() 指定索引
.id() 设置该文档的id 如果不设置则会自动生成
.document() 具体的对象
我这里用的TProduct 更换成自己需要检索的分词结构即可。
返回ResultJson 只是一个通用类不重要。
查看代码
public ResultJson uploadProduct(TProduct tProduct) {
IndexRequest<TProduct> req ;
req = IndexRequest.of( b->
b.index("product").id(tProduct.getProductId()+"").document(tProduct));
try {
elasticsearchClient.index(req);
return ResultJson.success();
} catch (IOException e) {
return ResultJson.failure(e.toString());
}
}
修改指定索引的对应ID的文档内容
.index() 指定索引
.id() 要修改的文档的id,我上面上传是用的TProduct对象的productId,所以这里也用这个属性来更新
.doc() 修改后的对象
public ResultJson updateDocument(TProduct tProduct){
UpdateRequest<TProduct,TProduct> req;
req = UpdateRequest.of(
b-> b.index("product").id(tProduct.getProductId()+"")
.doc(tProduct)
);
try {
elasticsearchClient.update(req,TProduct.class);
return ResultJson.success();
} catch (IOException e) {
return ResultJson.failure(e.toString());
}
}
删除指定索引的文档
.index() 指定索引
.id() 要删除的文档的id,我上面上传是用的TProduct对象的productId,所以这里也用这个属性来更新
查看代码
public ResultJson deleteDocument(Long productId){
DeleteRequest req ;
req = DeleteRequest.of(
b-> b.index("product").id(productId+"")
);
try {
elasticsearchClient.delete(req);
return ResultJson.success();
} catch (IOException e) {
return ResultJson.failure(e.toString());
}
}
查询
tProductList 存放最后查询hit到的结果集
调用客户端的search方法,目前只写了个matchQuery模糊查询,后面是拿到response的处理,官网复制粘贴的---复杂查询待补充
查看代码
public ResultJson queryTest(String name) throws IOException {
List<TProduct> tProductList = new ArrayList<>();
SearchResponse<TProduct> response = elasticsearchClient.search(
s -> s.index("product")
.query(
q -> q.match(
t -> t.field("productName")
.query(name)
)
)
,
TProduct.class
);
TotalHits total = response.hits().total();
boolean isExactResult = total.relation() == TotalHitsRelation.Eq;
if (isExactResult) {
log.info("There are {} results", total.value());
} else {
log.info("There are more than {} results", total.value());
}
List<Hit<TProduct>> hits = response.hits().hits();
for (Hit<TProduct> hit : hits) {
TProduct product = hit.source();
tProductList.add(product);
}
return ResultJson.success(tProductList);
}