使用Elasticsearch与Java进行全文搜索
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
// 假设你已经有了一个RestHighLevelClient实例client
public void searchWithElasticsearch(RestHighLevelClient client, String indexName, String searchText) throws IOException {
// 创建一个新的搜索请求
SearchRequest searchRequest = new SearchRequest(indexName);
// 构建搜索源构建器
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 添加查询条件
searchSourceBuilder.query(QueryBuilders.matchQuery("content", searchText));
// 按相关性排序
searchSourceBuilder.sort("_score", SortOrder.DESC);
// 设置搜索源
searchRequest.source(searchSourceBuilder);
// 执行搜索
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
// 处理搜索结果
// ...
}
这段代码展示了如何使用Elasticsearch Java API在指定索引中执行全文搜索。它设置了一个匹配查询来查找特定文本,并根据相关性对结果进行了排序。最终,你需要根据实际需求处理搜索结果。
评论已关闭