产品全站检索Elasticsearch使用代码案例
时间: 2023-12-25 16:55:01 浏览: 89
以下是一个简单的使用Java语言操作Elasticsearch实现全站检索的代码案例:
```java
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
public class ElasticsearchSearch {
private RestHighLevelClient client;
public ElasticsearchSearch(RestHighLevelClient client) {
this.client = client;
}
public SearchResponse search(String keyword) throws IOException {
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("content", keyword));
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("index_name");
searchRequest.source(searchSourceBuilder);
return client.search(searchRequest, RequestOptions.DEFAULT);
}
}
```
其中,`RestHighLevelClient`是Elasticsearch官方提供的Java客户端,`search()`方法接受一个关键词作为参数,使用`QueryBuilders.matchQuery()`方法构建查询条件,将查询请求发送至`index_name`所代表的索引,并返回`SearchResponse`对象,其中包含了搜索结果。
阅读全文