Elasticsearch基础篇:常用查询以及使用Java Api Client进行检索
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;
import org.elasticsearch.search.SearchHits;
import java.io.IOException;
public class ElasticSearchQueryExample {
public static void main(String[] args) throws IOException {
// 初始化Elasticsearch客户端
try (RestHighLevelClient client = new RestHighLevelClient(...)) {
// 创建查询请求并设置索引
SearchRequest searchRequest = new SearchRequest("index_name");
// 构建查询条件
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("field_name", "value"));
// 设置查询请求的源构建器
searchRequest.source(searchSourceBuilder);
// 执行查询
SearchResponse searchResponse = client.search(searchRequest);
// 处理查询结果
SearchHits searchHits = searchResponse.getHits();
for (SearchHit hit : searchHits) {
System.out.println(hit.getSourceAsString());
}
}
}
}
这段代码展示了如何使用Elasticsearch Java API Client进行基本的查询操作。它创建了一个匹配查询,查询字段field\_name的值为"value"的文档,并打印出返回结果的文档源数据。这是Elasticsearch搜索操作的基本示例,适用于入门级的Elasticsearch使用者。
评论已关闭