java调用ElasticSearch查询 字段keyword为string类型 等于199 和 字段kpi1值大于0 或kpi2值大于0
时间: 2023-12-10 14:37:38 浏览: 102
可以使用Elasticsearch的Java API来实现这个查询。首先建立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.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import java.io.IOException;
public class ElasticsearchQuery {
public static void main(String[] args) throws IOException {
// 建立连接
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 构建查询条件
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
boolQuery.must(QueryBuilders.termQuery("keyword", "199"));
boolQuery.should(QueryBuilders.rangeQuery("kpi1").gt(0));
boolQuery.should(QueryBuilders.rangeQuery("kpi2").gt(0));
// 构建搜索请求
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(boolQuery);
sourceBuilder.sort("timestamp", SortOrder.DESC);
SearchRequest searchRequest = new SearchRequest("index_name");
searchRequest.source(sourceBuilder);
// 执行查询
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
// 处理查询结果
// ...
// 关闭连接
client.close();
}
}
```
上面的代码中,“index_name”需要替换成实际的索引名称。这个查询使用了bool查询和term查询来匹配“keyword=199”,使用should子句来匹配“kpi1>0”或“kpi2>0”。最后将结果按照“timestamp”字段降序排列。你可以根据实际需要修改查询条件和排序方式。
阅读全文