ElasticSearch与项目的整合使用
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
// 假设已经有一个初始化好的RestHighLevelClient实例client
public SearchResponse search(RestHighLevelClient client, String indexName, String fieldName, String queryString) throws IOException {
SearchRequest searchRequest = new SearchRequest(indexName);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery(fieldName, queryString));
searchSourceBuilder.sort(fieldName, SortOrder.ASC);
searchSourceBuilder.size(10); // 设置返回结果的最大数量
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
return searchResponse;
}
// 使用示例
public static void main(String[] args) throws IOException {
// 初始化Elasticsearch客户端
RestHighLevelClient client = new RestHighLevelClient(...);
// 调用search方法
SearchResponse response = search(client, "index_name", "content", "查询字符串");
// 处理搜索结果
// ...
// 关闭客户端
client.close();
}
这个代码示例展示了如何使用Elasticsearch Java API进行搜索操作。它定义了一个search
方法,该方法接受Elasticsearch客户端、索引名、字段名和查询字符串作为参数,执行匹配查询并按指定字段升序排序,返回前10条结果。在main
方法中,我们可以看到如何初始化客户端,调用search
方法,以及最后关闭客户端资源的示例。
评论已关闭