利用Elasticsearch提升Java应用的搜索能力
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
// 假设已经创建并配置好RestHighLevelClient实例client
RestHighLevelClient client;
public void searchWithElasticsearch(String indexName, String fieldName, String searchText) throws IOException {
// 构建搜索请求
SearchRequest searchRequest = new SearchRequest(indexName);
// 构建搜索源构建器
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery(fieldName, searchText)); // 使用match查询
searchRequest.source(searchSourceBuilder);
// 执行搜索
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
// 处理搜索结果
for (SearchHit hit : searchResponse.getHits().getHits()) {
System.out.println(hit.getSourceAsString());
}
}
这段代码展示了如何使用Elasticsearch Java API在指定索引中搜索特定字段包含特定文本的文档。代码中创建了一个搜索请求,并设置了搜索源构建器,其中定义了match查询用于搜索文档。然后执行搜索并打印返回结果的文档源。
评论已关闭