一文全览各种 ES 查询在 Java 中的实现
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
// 创建一个简单的匹配查询
QueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("fieldname", "text");
// 创建一个函数得分查询
FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery()
.add(ScoreFunctionBuilders.fieldValueFactorFunction("fieldname"))
.scoreMode("multiply")
.setMinScore(2);
// 创建一个布尔查询,结合必须匹配和最终可以匹配的查询
QueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
.must(QueryBuilders.matchQuery("fieldname", "text"))
.should(QueryBuilders.matchQuery("fieldname", "text2"));
// 创建一个范围查询
QueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("fieldname")
.gte("value1")
.lte("value2");
// 创建一个前缀查询
QueryBuilder prefixQueryBuilder = QueryBuilders.prefixQuery("fieldname", "prefix");
// 创建一个通配符查询
QueryBuilder wildcardQueryBuilder = QueryBuilders.wildcardQuery("fieldname", "te*t");
// 创建一个查询字符串查询
QueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery("fieldname:value AND otherfield:othervalue");
// 创建一个模糊查询
QueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("fieldname", "text");
// 创建一个组合查询
QueryBuilder constantScoreQueryBuilder = QueryBuilders.constantScoreQuery(QueryBuilders.matchAllQuery());
// 创建一个地理边界查询
QueryBuilder geoBoundingBoxQueryBuilder = QueryBuilders.geoBoundingBoxQuery("geofield")
.setCorners(40, -70, 40, -100);
// 创建一个地理距离查询
QueryBuilder geoDistanceQueryBuilder = QueryBuilders.geoDistanceQuery("geofield")
.point(40, -70)
.distance(100, DistanceUnit.KILOMETERS);
// 创建一个组合查询
QueryBuilder boolQueryBuilderCombined = QueryBuilders.boolQuery()
.must(matchQueryBuilder)
.should(prefixQueryBuilder)
.filter(rangeQueryBuilder);
这段代码展示了如何在Java中使用Elasticsearch的QueryBuilders API来创建各种不同类型的查询。每个查询都是用特定的查询类型创建的,并且可以根据需要进行定制,例如设置字段值、范围、前缀等。这些查询可
评论已关闭