private SearchResponse minMaxQuery(ScoreMode scoreMode, int minChildren, Integer maxChildren) throws SearchPhaseExecutionException { HasChildQueryBuilder hasChildQuery = hasChildQuery( "child", QueryBuilders.functionScoreQuery(constantScoreQuery(QueryBuilders.termQuery("foo", "two")), new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{ new FunctionScoreQueryBuilder.FilterFunctionBuilder(weightFactorFunction(1)), new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("foo", "three"), weightFactorFunction(1)), new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("foo", "four"), weightFactorFunction(1)) }).boostMode(CombineFunction.REPLACE).scoreMode(FiltersFunctionScoreQuery.ScoreMode.SUM), scoreMode) .minMaxChildren(minChildren, maxChildren != null ? maxChildren : HasChildQueryBuilder.DEFAULT_MAX_CHILDREN); return client() .prepareSearch("test") .setQuery(hasChildQuery) .addSort("_score", SortOrder.DESC).addSort("id", SortOrder.ASC).get(); }
public void testUnsupportedQueries() { RangeQueryBuilder rangeQuery1 = new RangeQueryBuilder("field").from("2016-01-01||/D").to("2017-01-01||/D"); RangeQueryBuilder rangeQuery2 = new RangeQueryBuilder("field").from("2016-01-01||/D").to("now"); PercolatorFieldMapper.verifyQuery(rangeQuery1); expectThrows(IllegalArgumentException.class, () -> PercolatorFieldMapper.verifyQuery(rangeQuery2)); PercolatorFieldMapper.verifyQuery(new BoolQueryBuilder().must(rangeQuery1)); expectThrows(IllegalArgumentException.class, () -> PercolatorFieldMapper.verifyQuery(new BoolQueryBuilder().must(rangeQuery2))); PercolatorFieldMapper.verifyQuery(new ConstantScoreQueryBuilder((rangeQuery1))); expectThrows(IllegalArgumentException.class, () -> PercolatorFieldMapper.verifyQuery(new ConstantScoreQueryBuilder(rangeQuery2))); PercolatorFieldMapper.verifyQuery(new BoostingQueryBuilder(rangeQuery1, new MatchAllQueryBuilder())); expectThrows(IllegalArgumentException.class, () -> PercolatorFieldMapper.verifyQuery(new BoostingQueryBuilder(rangeQuery2, new MatchAllQueryBuilder()))); PercolatorFieldMapper.verifyQuery(new FunctionScoreQueryBuilder(rangeQuery1, new RandomScoreFunctionBuilder())); expectThrows(IllegalArgumentException.class, () -> PercolatorFieldMapper.verifyQuery(new FunctionScoreQueryBuilder(rangeQuery2, new RandomScoreFunctionBuilder()))); HasChildQueryBuilder hasChildQuery = new HasChildQueryBuilder("_type", new MatchAllQueryBuilder(), ScoreMode.None); expectThrows(IllegalArgumentException.class, () -> PercolatorFieldMapper.verifyQuery(hasChildQuery)); expectThrows(IllegalArgumentException.class, () -> PercolatorFieldMapper.verifyQuery(new BoolQueryBuilder().must(hasChildQuery))); HasParentQueryBuilder hasParentQuery = new HasParentQueryBuilder("_type", new MatchAllQueryBuilder(), false); expectThrows(IllegalArgumentException.class, () -> PercolatorFieldMapper.verifyQuery(hasParentQuery)); expectThrows(IllegalArgumentException.class, () -> PercolatorFieldMapper.verifyQuery(new BoolQueryBuilder().must(hasParentQuery))); }
@Override public List<City> searchCity(Integer pageNumber, Integer pageSize, String searchContent) { // 分页参数 Pageable pageable = new PageRequest(pageNumber, pageSize); // Function Score Query FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery() .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("cityname", searchContent)), ScoreFunctionBuilders.weightFactorFunction(1000)) .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("description", searchContent)), ScoreFunctionBuilders.weightFactorFunction(100)); // 创建搜索 DSL 查询 SearchQuery searchQuery = new NativeSearchQueryBuilder() .withPageable(pageable) .withQuery(functionScoreQueryBuilder).build(); LOGGER.info("\n searchCity(): searchContent [" + searchContent + "] \n DSL = \n " + searchQuery.getQuery().toString()); Page<City> searchPageResults = cityRepository.search(searchQuery); return searchPageResults.getContent(); }
/** * 根据搜索词构造搜索查询语句 * * 代码流程: * - 权重分查询 * - 短语匹配 * - 设置权重分最小值 * - 设置分页参数 * * @param pageNumber 当前页码 * @param pageSize 每页大小 * @param searchContent 搜索内容 * @return */ private SearchQuery getCitySearchQuery(Integer pageNumber, Integer pageSize,String searchContent) { // 短语匹配到的搜索词,求和模式累加权重分 // 权重分查询 https://www.elastic.co/guide/cn/elasticsearch/guide/current/function-score-query.html // - 短语匹配 https://www.elastic.co/guide/cn/elasticsearch/guide/current/phrase-matching.html // - 字段对应权重分设置,可以优化成 enum // - 由于无相关性的分值默认为 1 ,设置权重分最小值为 10 FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery() .add(QueryBuilders.matchPhraseQuery("name", searchContent), ScoreFunctionBuilders.weightFactorFunction(1000)) .add(QueryBuilders.matchPhraseQuery("description", searchContent), ScoreFunctionBuilders.weightFactorFunction(500)) .scoreMode(SCORE_MODE_SUM).setMinScore(MIN_SCORE); // 分页参数 Pageable pageable = new PageRequest(pageNumber, pageSize); return new NativeSearchQueryBuilder() .withPageable(pageable) .withQuery(functionScoreQueryBuilder).build(); }
/** * * * * @param pageNumber * @param pageSize * @param searchContent * @return */ public List<GoodsModel> searchGoods(Integer pageNumber, Integer pageSize, String searchContent) { // 分页参数 Pageable pageable = new PageRequest(pageNumber, pageSize); // Function Score Query FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery() .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("goodsName", searchContent)),ScoreFunctionBuilders.weightFactorFunction(1000)) .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("description", searchContent)),ScoreFunctionBuilders.weightFactorFunction(1000)); // 创建搜索 DSL 查询 SearchQuery searchQuery = new NativeSearchQueryBuilder() .withPageable(pageable) .withQuery(functionScoreQueryBuilder).build(); logger.info("\n searchGoods(): searchContent [" + searchContent + "] \n DSL = \n " + searchQuery.getQuery().toString()); Page<GoodsModel> searchPageResults = goodsESDocRepository.search(searchQuery); return searchPageResults.getContent(); }
@Before public void setUp() throws Exception { super.setUp(); store.clear(); StoredFeature feature1 = new StoredFeature("match1", Collections.singletonList("query_string"), "mustache", new MatchQueryBuilder("field1", "{{query_string}}").toString()); StoredFeature feature2 = new StoredFeature("match2", Collections.singletonList("query_string"), "mustache", new MatchQueryBuilder("field2", "{{query_string}}").toString()); StoredFeature feature3 = new StoredFeature("score3", Collections.emptyList(), "mustache", new FunctionScoreQueryBuilder(new FieldValueFactorFunctionBuilder("scorefield2") .factor(1.2F) .modifier(FieldValueFactorFunction.Modifier.LN2P) .missing(0F)).toString()); StoredFeatureSet set = new StoredFeatureSet("set1", Arrays.asList(feature1, feature2, feature3)); store.add(set); LtrRanker ranker = new LinearRanker(new float[]{0.1F, 0.2F, 0.3F}); CompiledLtrModel model = new CompiledLtrModel("model1", set, ranker); store.add(model); }
public void prepareModels() throws Exception { List<StoredFeature> features = new ArrayList<>(3); features.add(new StoredFeature("text_feature1", Collections.singletonList("query"), "mustache", QueryBuilders.matchQuery("field1", "{{query}}").toString())); features.add(new StoredFeature("text_feature2", Collections.singletonList("query"), "mustache", QueryBuilders.matchQuery("field2", "{{query}}").toString())); features.add(new StoredFeature("numeric_feature1", Collections.singletonList("query"), "mustache", new FunctionScoreQueryBuilder(QueryBuilders.matchAllQuery(), new FieldValueFactorFunctionBuilder("scorefield1") .factor(FACTOR) .modifier(FieldValueFactorFunction.Modifier.LN2P) .missing(0F)).scoreMode(FiltersFunctionScoreQuery.ScoreMode.MULTIPLY).toString())); features.add(new StoredFeature("derived_feature", Collections.singletonList("query"), "derived_expression", "100")); StoredFeatureSet set = new StoredFeatureSet("my_set", features); addElement(set); StoredLtrModel model = new StoredLtrModel("my_model", set, new StoredLtrModel.LtrModelDefinition("model/linear", LinearRankerParserTests.generateRandomModelString(set), true)); addElement(model); }
protected QueryBuilder buildFunctionScoreQuery(final String query, final QueryBuilder queryBuilder) { final List<FunctionScoreQueryBuilder.FilterFunctionBuilder> flist = new ArrayList<>(); if (isSingleWordQuery(query) && !isHiraganaQuery(query)) { flist.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.prefixQuery(FieldNames.TEXT, query), ScoreFunctionBuilders.weightFactorFunction(prefixMatchWeight))); } flist.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(ScoreFunctionBuilders.fieldValueFactorFunction(FieldNames.DOC_FREQ) .missing(0.1f).modifier(FieldValueFactorFunction.Modifier.LOG2P).setWeight(1.0F))); flist.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(ScoreFunctionBuilders.fieldValueFactorFunction(FieldNames.QUERY_FREQ) .missing(0.1f).modifier(FieldValueFactorFunction.Modifier.LOG2P).setWeight(1.0F))); flist.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(ScoreFunctionBuilders.fieldValueFactorFunction(FieldNames.USER_BOOST) .missing(1f).setWeight(1.0F))); final FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(queryBuilder, flist.toArray(new FunctionScoreQueryBuilder.FilterFunctionBuilder[flist.size()])); functionScoreQueryBuilder.boostMode(CombineFunction.REPLACE); functionScoreQueryBuilder.scoreMode(FunctionScoreQuery.ScoreMode.MULTIPLY); return functionScoreQueryBuilder; }
public void testFunctionScore() { FilterFunctionBuilder[] functions = { new FunctionScoreQueryBuilder.FilterFunctionBuilder( matchQuery("name", "kimchy"), randomFunction("ABCDEF")), new FunctionScoreQueryBuilder.FilterFunctionBuilder( exponentialDecayFunction("age", 0L, 1L)) }; functionScoreQuery(functions); }
public void testInlineLeafInnerHitsNestedQueryViaFunctionScoreQuery() { InnerHitBuilder leafInnerHits = randomInnerHits(); NestedQueryBuilder nestedQueryBuilder = new NestedQueryBuilder("path", new MatchAllQueryBuilder(), ScoreMode.None) .innerHit(leafInnerHits, false); FunctionScoreQueryBuilder functionScoreQueryBuilder = new FunctionScoreQueryBuilder(nestedQueryBuilder); Map<String, InnerHitBuilder> innerHitBuilders = new HashMap<>(); ((AbstractQueryBuilder<?>) functionScoreQueryBuilder).extractInnerHitBuilders(innerHitBuilders); assertThat(innerHitBuilders.get(leafInnerHits.getName()), notNullValue()); }
@Test public void test() throws Exception { FunctionScoreQueryBuilder.FilterFunctionBuilder [] filterFunctionBuilders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[] { new FunctionScoreQueryBuilder.FilterFunctionBuilder(ScoreFunctionBuilders.scriptFunction("doc['pubTime'].value*0.00000000001")), new FunctionScoreQueryBuilder.FilterFunctionBuilder(ScoreFunctionBuilders.scriptFunction("doc['opinionValue'].value*0.1")), }; QueryBuilders.functionScoreQuery( QueryBuilders.queryStringQuery("北京").defaultField("FIELD").field("titleZh^3.0"), filterFunctionBuilders ).boostMode(CombineFunction.MULTIPLY).scoreMode(FiltersFunctionScoreQuery.ScoreMode.AVG); }
@Test public void testForClient() throws Exception { FunctionScoreQueryBuilder.FilterFunctionBuilder[] functions = { new FunctionScoreQueryBuilder.FilterFunctionBuilder( QueryBuilders.matchQuery("name", "kimchy"), ScoreFunctionBuilders. randomFunction("ABCDEF")), new FunctionScoreQueryBuilder.FilterFunctionBuilder( ScoreFunctionBuilders.exponentialDecayFunction("age", 0L, 1L)) }; QueryBuilder qb = QueryBuilders.functionScoreQuery(functions); client.prepareSearch().setQuery(qb).execute().actionGet(); }
@Nullable String getClosestId(int limit) { @SuppressWarnings("unchecked") Map<String, Object> primaryLocation = (Map<String, Object>) featureStructure.get("primaryLocation"); BoolQueryBuilder boolQueryBuilder = target.queryInDocument(documentId); if (primaryLocation == null || !primaryLocation.containsKey("begin") || !primaryLocation.containsKey("end")) { return null; } SearchResponse searchResponse; if (limit != 0) { FunctionScoreQueryBuilder query = new FunctionScoreQueryBuilder(boolQueryBuilder) .add(ScoreFunctionBuilders.scriptFunction(new Script("annotationDistance", ScriptService.ScriptType.INLINE, "native", primaryLocation))); float minScore = 1.0f / (limit + 1.0f); searchResponse = client.prepareSearch(target.getSystemIndex()) .setQuery(query) .setMinScore(minScore) .execute().actionGet(); } else { searchResponse = client.prepareSearch(target.getSystemIndex()) .setQuery(boolQueryBuilder.must(QueryBuilders.termQuery("primaryLocation.begin", primaryLocation.get("begin"))) .must(QueryBuilders.termQuery("primaryLocation.end", primaryLocation.get("end")))) .get(); } SearchHit[] hits = searchResponse.getHits().hits(); if (hits.length > 0) { return hits[0].getId(); } return null; }
/** * 构建查询 * * @return */ public QueryBuilder makeQueryBuilder(SearchRequestBuilder srb) { // 拼接查询层次 BoolQueryBuilder boolQ = QueryBuilders.boolQuery(); Map<SearchCondition, ConditionType> searchTypeMap = this.request.getSearchConditions(); ConditionType conditionType; BoolQueryBuilder subBoolQ; for (SearchCondition searchCondition : searchTypeMap.keySet()) { conditionType = searchTypeMap.get(searchCondition); subBoolQ = queryBuilder(searchCondition, conditionType); mergeBuilder(boolQ, subBoolQ, conditionType); } // 没有条件直接返回 if (!boolQ.hasClauses()) { return null; } // 得分脚本 if (request.getSafeScoreScript().size() < 1) { srb.setQuery(boolQ); return boolQ; } String boost_mode = request.getSafeExtend().get(Constants.BOOST_MODE_KEY); if (StringUtils.isBlank(boost_mode)) { boost_mode = Constants.boost_mode; } FunctionScoreQueryBuilder functionScoreQ = QueryBuilders.functionScoreQuery(boolQ); functionScoreQ.boostMode(boost_mode); for (ScoreScript scoreScript : request.getSafeScoreScript()) { ScriptScoreFunctionBuilder builder = ScoreFunctionBuilders.scriptFunction(scoreScript .getScript()); if (scoreScript.getScriptParams() != null && scoreScript.getScriptParams().size() > 0) { builder.params(scoreScript.getScriptParams()); } functionScoreQ.add(builder); } srb.setQuery(functionScoreQ); return functionScoreQ; }
/** * Processes the scripts and score function * * @param queryBuilder the query builder * * @return the function score query builder */ private FunctionScoreQueryBuilder getFunctionScoreQueryBuilder(QueryBuilder queryBuilder, String bdefActiveIndex) { // Script for tag search score multiplier. If bdef set to tag search score multiplier else set to a default value. String inlineScript = "_score * (doc['_index'].value == '" + bdefActiveIndex + "' ? doc['" + BDEF_TAGS_SEARCH_SCORE_MULTIPLIER + "']: 1)"; // Set the lang to groovy Script script = new Script(ScriptType.INLINE, "groovy", inlineScript, Collections.emptyMap()); // Set the script ScriptScoreFunctionBuilder scoreFunction = ScoreFunctionBuilders.scriptFunction(script); // Create function score query builder return new FunctionScoreQueryBuilder(queryBuilder, scoreFunction); }
protected QueryBuilder getQueryBuilder(SearchCriteria searchCriteria) { QueryBuilder matchQueryBuilder = null; String queryString = searchCriteria.getQuery(); if (StringUtils.isBlank(queryString)) { matchQueryBuilder = QueryBuilders.matchAllQuery(); } else { final String filterSpecialCharsQueryString = escapeQueryChars(queryString); final QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryString(filterSpecialCharsQueryString); // Add fields queryStringQueryBuilder.field(SearchDocumentFieldName.TITLE.getFieldName(), (float) 0.5) .field(SearchDocumentFieldName.DESCRIPTION.getFieldName(), (float) 0.15) ; for (final String contentCategoryFieldName : SearchFacetName.categoryFacetFields) { queryStringQueryBuilder.field(SearchDocumentFieldName.CATEGORIES_ARRAY.getFieldName() + "." + contentCategoryFieldName, 1); } matchQueryBuilder = queryStringQueryBuilder; } if(searchCriteria.isUseBoostingFactor()) { FunctionScoreQueryBuilder queryBuilder = new FunctionScoreQueryBuilder(matchQueryBuilder); ScoreFunctionBuilder scoreFunctionBuilder = new ScriptScoreFunctionBuilder().script(SearchDocumentFieldName .getCalculatedScoreScriptForBostFactor()); queryBuilder.add(scoreFunctionBuilder); return queryBuilder; } return matchQueryBuilder; }
protected QueryBuilder getQueryBuilder(final SearchCriteria searchCriteria) { QueryBuilder matchQueryBuilder = null; final String queryString = searchCriteria.getQuery(); if (StringUtils.isBlank(queryString)) { matchQueryBuilder = QueryBuilders.matchAllQuery(); } else { final String filterSpecialCharsQueryString = escapeQueryChars(queryString); final QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryString(filterSpecialCharsQueryString); // Add fields queryStringQueryBuilder.field(SearchDocumentFieldName.TITLE.getFieldName(), (float) 0.5).field( SearchDocumentFieldName.DESCRIPTION.getFieldName(), (float) 0.15); for (final String contentCategoryFieldName : SearchFacetName.categoryFacetFields) { queryStringQueryBuilder.field(SearchDocumentFieldName.CATEGORIES_ARRAY.getFieldName() + "." + contentCategoryFieldName, 1); } matchQueryBuilder = queryStringQueryBuilder; } if (searchCriteria.isUseBoostingFactor()) { final FunctionScoreQueryBuilder queryBuilder = new FunctionScoreQueryBuilder(matchQueryBuilder); final ScoreFunctionBuilder scoreFunctionBuilder = new ScriptScoreFunctionBuilder().script(SearchDocumentFieldName .getCalculatedScoreScriptForBostFactor()); queryBuilder.add(scoreFunctionBuilder); return queryBuilder; } return matchQueryBuilder; }
private static QueryBuilder boostWrapMatchAllWithFunctionScore(QueryBuilder qb, String term, String boostFields){ String[] fields = boostFields.split(","); BoolQueryBuilder query = QueryBuilders.boolQuery(); for(String field : fields){ query.should(QueryBuilders.matchQuery(field, term)); } FunctionScoreQueryBuilder fsqb = QueryBuilders.functionScoreQuery(query).add(ScoreFunctionBuilders.weightFactorFunction(10)); return QueryBuilders.boolQuery().should(qb).should(fsqb); }
protected QueryBuilder getQueryBuilder(final SearchCriteria searchCriteria) { QueryBuilder matchQueryBuilder = null; final String queryString = searchCriteria.getQuery(); if (StringUtils.isBlank(queryString)) { matchQueryBuilder = QueryBuilders.matchAllQuery(); } else { final String filterSpecialCharsQueryString = escapeQueryChars(queryString); final QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders .queryString(filterSpecialCharsQueryString); // Add fields queryStringQueryBuilder.field( SearchDocumentFieldName.TITLE.getFieldName(), (float) 0.5) .field(SearchDocumentFieldName.DESCRIPTION.getFieldName(), (float) 0.15); for (final String contentCategoryFieldName : SearchFacetName.categoryFacetFields) { queryStringQueryBuilder.field( SearchDocumentFieldName.CATEGORIES_ARRAY.getFieldName() + "." + contentCategoryFieldName, 1); } matchQueryBuilder = queryStringQueryBuilder; } if (searchCriteria.isUseBoostingFactor()) { final FunctionScoreQueryBuilder queryBuilder = new FunctionScoreQueryBuilder( matchQueryBuilder); final ScoreFunctionBuilder scoreFunctionBuilder = new ScriptScoreFunctionBuilder() .script(SearchDocumentFieldName .getCalculatedScoreScriptForBostFactor()); queryBuilder.add(scoreFunctionBuilder); return queryBuilder; } return matchQueryBuilder; }
protected QueryBuilder buildQuery() { final BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery(); queryBuilder.must(QueryBuilders.termQuery(FieldNames.KINDS, SuggestItem.Kind.QUERY.toString())); queryBuilder.mustNot(QueryBuilders.existsQuery(FieldNames.READING_PREFIX + "1")); queryBuilder.must(QueryBuilders.rangeQuery(FieldNames.QUERY_FREQ).gte(queryFreqThreshold)); if (!tags.isEmpty()) { queryBuilder.must(QueryBuilders.termsQuery(FieldNames.TAGS, tags)); } if (!roles.isEmpty()) { queryBuilder.must(QueryBuilders.termsQuery(FieldNames.ROLES, roles)); } else { queryBuilder.must(QueryBuilders.termQuery(FieldNames.ROLES, SuggestConstants.DEFAULT_ROLE)); } if (!fields.isEmpty()) { queryBuilder.must(QueryBuilders.termsQuery(FieldNames.FIELDS, fields)); } if (!excludeWords.isEmpty()) { queryBuilder.mustNot(QueryBuilders.termsQuery(FieldNames.TEXT, excludeWords)); } ; final FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(queryBuilder, ScoreFunctionBuilders.fieldValueFactorFunction(FieldNames.QUERY_FREQ) .missing(0)); functionScoreQueryBuilder.boostMode(CombineFunction.REPLACE); return functionScoreQueryBuilder; }
private void registerQueryParsers(List<SearchPlugin> plugins) { registerQuery(new QuerySpec<>(MatchQueryBuilder.NAME, MatchQueryBuilder::new, MatchQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(MatchPhraseQueryBuilder.NAME, MatchPhraseQueryBuilder::new, MatchPhraseQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(MatchPhrasePrefixQueryBuilder.NAME, MatchPhrasePrefixQueryBuilder::new, MatchPhrasePrefixQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(MultiMatchQueryBuilder.NAME, MultiMatchQueryBuilder::new, MultiMatchQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(NestedQueryBuilder.NAME, NestedQueryBuilder::new, NestedQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(HasChildQueryBuilder.NAME, HasChildQueryBuilder::new, HasChildQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(HasParentQueryBuilder.NAME, HasParentQueryBuilder::new, HasParentQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(DisMaxQueryBuilder.NAME, DisMaxQueryBuilder::new, DisMaxQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(IdsQueryBuilder.NAME, IdsQueryBuilder::new, IdsQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(MatchAllQueryBuilder.NAME, MatchAllQueryBuilder::new, MatchAllQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(QueryStringQueryBuilder.NAME, QueryStringQueryBuilder::new, QueryStringQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(BoostingQueryBuilder.NAME, BoostingQueryBuilder::new, BoostingQueryBuilder::fromXContent)); BooleanQuery.setMaxClauseCount(INDICES_MAX_CLAUSE_COUNT_SETTING.get(settings)); registerQuery(new QuerySpec<>(BoolQueryBuilder.NAME, BoolQueryBuilder::new, BoolQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(TermQueryBuilder.NAME, TermQueryBuilder::new, TermQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(TermsQueryBuilder.NAME, TermsQueryBuilder::new, TermsQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(FuzzyQueryBuilder.NAME, FuzzyQueryBuilder::new, FuzzyQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(RegexpQueryBuilder.NAME, RegexpQueryBuilder::new, RegexpQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(RangeQueryBuilder.NAME, RangeQueryBuilder::new, RangeQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(PrefixQueryBuilder.NAME, PrefixQueryBuilder::new, PrefixQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(WildcardQueryBuilder.NAME, WildcardQueryBuilder::new, WildcardQueryBuilder::fromXContent)); registerQuery( new QuerySpec<>(ConstantScoreQueryBuilder.NAME, ConstantScoreQueryBuilder::new, ConstantScoreQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(SpanTermQueryBuilder.NAME, SpanTermQueryBuilder::new, SpanTermQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(SpanNotQueryBuilder.NAME, SpanNotQueryBuilder::new, SpanNotQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(SpanWithinQueryBuilder.NAME, SpanWithinQueryBuilder::new, SpanWithinQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(SpanContainingQueryBuilder.NAME, SpanContainingQueryBuilder::new, SpanContainingQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(FieldMaskingSpanQueryBuilder.NAME, FieldMaskingSpanQueryBuilder::new, FieldMaskingSpanQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(SpanFirstQueryBuilder.NAME, SpanFirstQueryBuilder::new, SpanFirstQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(SpanNearQueryBuilder.NAME, SpanNearQueryBuilder::new, SpanNearQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(SpanOrQueryBuilder.NAME, SpanOrQueryBuilder::new, SpanOrQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(MoreLikeThisQueryBuilder.NAME, MoreLikeThisQueryBuilder::new, MoreLikeThisQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(WrapperQueryBuilder.NAME, WrapperQueryBuilder::new, WrapperQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(CommonTermsQueryBuilder.NAME, CommonTermsQueryBuilder::new, CommonTermsQueryBuilder::fromXContent)); registerQuery( new QuerySpec<>(SpanMultiTermQueryBuilder.NAME, SpanMultiTermQueryBuilder::new, SpanMultiTermQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(FunctionScoreQueryBuilder.NAME, FunctionScoreQueryBuilder::new, FunctionScoreQueryBuilder::fromXContent)); registerQuery( new QuerySpec<>(SimpleQueryStringBuilder.NAME, SimpleQueryStringBuilder::new, SimpleQueryStringBuilder::fromXContent)); registerQuery(new QuerySpec<>(TypeQueryBuilder.NAME, TypeQueryBuilder::new, TypeQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(ScriptQueryBuilder.NAME, ScriptQueryBuilder::new, ScriptQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(GeoDistanceQueryBuilder.NAME, GeoDistanceQueryBuilder::new, GeoDistanceQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(GeoBoundingBoxQueryBuilder.NAME, GeoBoundingBoxQueryBuilder::new, GeoBoundingBoxQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(GeoPolygonQueryBuilder.NAME, GeoPolygonQueryBuilder::new, GeoPolygonQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(ExistsQueryBuilder.NAME, ExistsQueryBuilder::new, ExistsQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(MatchNoneQueryBuilder.NAME, MatchNoneQueryBuilder::new, MatchNoneQueryBuilder::fromXContent)); registerQuery(new QuerySpec<>(ParentIdQueryBuilder.NAME, ParentIdQueryBuilder::new, ParentIdQueryBuilder::fromXContent)); if (ShapesAvailability.JTS_AVAILABLE && ShapesAvailability.SPATIAL4J_AVAILABLE) { registerQuery(new QuerySpec<>(GeoShapeQueryBuilder.NAME, GeoShapeQueryBuilder::new, GeoShapeQueryBuilder::fromXContent)); } registerFromPlugin(plugins, SearchPlugin::getQueries, this::registerQuery); }
public void testParseGeoPoint() throws Exception { assertAcked(prepareCreate("test").addMapping( "type1", jsonBuilder().startObject().startObject("type1").startObject("properties").startObject("test").field("type", "text") .endObject().startObject("loc").field("type", "geo_point").endObject().endObject().endObject().endObject())); client().prepareIndex() .setType("type1") .setId("1") .setIndex("test") .setSource( jsonBuilder().startObject() .field("test", "value") .startObject("loc") .field("lat", 20) .field("lon", 11) .endObject() .endObject()).setRefreshPolicy(IMMEDIATE).get(); FunctionScoreQueryBuilder baseQuery = functionScoreQuery(constantScoreQuery(termQuery("test", "value")), ScoreFunctionBuilders.weightFactorFunction(randomIntBetween(1, 10))); GeoPoint point = new GeoPoint(20, 11); ActionFuture<SearchResponse> response = client().search( searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( searchSource().query( functionScoreQuery(baseQuery, gaussDecayFunction("loc", point, "1000km")).boostMode( CombineFunction.REPLACE)))); SearchResponse sr = response.actionGet(); SearchHits sh = sr.getHits(); assertThat(sh.getTotalHits(), equalTo((long) (1))); assertThat(sh.getAt(0).getId(), equalTo("1")); assertThat((double) sh.getAt(0).getScore(), closeTo(1.0, 1.e-5)); // this is equivalent to new GeoPoint(20, 11); just flipped so scores must be same float[] coords = { 11, 20 }; response = client().search( searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( searchSource().query( functionScoreQuery(baseQuery, gaussDecayFunction("loc", coords, "1000km")).boostMode( CombineFunction.REPLACE)))); sr = response.actionGet(); sh = sr.getHits(); assertThat(sh.getTotalHits(), equalTo((long) (1))); assertThat(sh.getAt(0).getId(), equalTo("1")); assertThat((double) sh.getAt(0).getScore(), closeTo(1.0f, 1.e-5)); }
public void testCombineModes() throws Exception { assertAcked(prepareCreate("test").addMapping( "type1", jsonBuilder().startObject().startObject("type1").startObject("properties").startObject("test").field("type", "text") .endObject().startObject("num").field("type", "double").endObject().endObject().endObject().endObject())); client().prepareIndex().setType("type1").setId("1").setIndex("test").setRefreshPolicy(IMMEDIATE) .setSource(jsonBuilder().startObject().field("test", "value value").field("num", 1.0).endObject()).get(); FunctionScoreQueryBuilder baseQuery = functionScoreQuery(constantScoreQuery(termQuery("test", "value")), ScoreFunctionBuilders.weightFactorFunction(2)); // decay score should return 0.5 for this function and baseQuery should return 2.0f as it's score ActionFuture<SearchResponse> response = client().search( searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( searchSource().query( functionScoreQuery(baseQuery, gaussDecayFunction("num", 0.0, 1.0, null, 0.5)) .boostMode(CombineFunction.MULTIPLY)))); SearchResponse sr = response.actionGet(); SearchHits sh = sr.getHits(); assertThat(sh.getTotalHits(), equalTo((long) (1))); assertThat(sh.getAt(0).getId(), equalTo("1")); assertThat((double) sh.getAt(0).getScore(), closeTo(1.0, 1.e-5)); response = client().search( searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( searchSource().query( functionScoreQuery(baseQuery, gaussDecayFunction("num", 0.0, 1.0, null, 0.5)) .boostMode(CombineFunction.REPLACE)))); sr = response.actionGet(); sh = sr.getHits(); assertThat(sh.getTotalHits(), equalTo((long) (1))); assertThat(sh.getAt(0).getId(), equalTo("1")); assertThat((double) sh.getAt(0).getScore(), closeTo(0.5, 1.e-5)); response = client().search( searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( searchSource().query( functionScoreQuery(baseQuery, gaussDecayFunction("num", 0.0, 1.0, null, 0.5)) .boostMode(CombineFunction.SUM)))); sr = response.actionGet(); sh = sr.getHits(); assertThat(sh.getTotalHits(), equalTo((long) (1))); assertThat(sh.getAt(0).getId(), equalTo("1")); assertThat((double) sh.getAt(0).getScore(), closeTo(2.0 + 0.5, 1.e-5)); logger.info("--> Hit[0] {} Explanation:\n {}", sr.getHits().getAt(0).getId(), sr.getHits().getAt(0).getExplanation()); response = client().search( searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( searchSource().query( functionScoreQuery(baseQuery, gaussDecayFunction("num", 0.0, 1.0, null, 0.5)) .boostMode(CombineFunction.AVG)))); sr = response.actionGet(); sh = sr.getHits(); assertThat(sh.getTotalHits(), equalTo((long) (1))); assertThat(sh.getAt(0).getId(), equalTo("1")); assertThat((double) sh.getAt(0).getScore(), closeTo((2.0 + 0.5) / 2, 1.e-5)); response = client().search( searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( searchSource().query( functionScoreQuery(baseQuery, gaussDecayFunction("num", 0.0, 1.0, null, 0.5)) .boostMode(CombineFunction.MIN)))); sr = response.actionGet(); sh = sr.getHits(); assertThat(sh.getTotalHits(), equalTo((long) (1))); assertThat(sh.getAt(0).getId(), equalTo("1")); assertThat((double) sh.getAt(0).getScore(), closeTo(0.5, 1.e-5)); response = client().search( searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( searchSource().query( functionScoreQuery(baseQuery, gaussDecayFunction("num", 0.0, 1.0, null, 0.5)) .boostMode(CombineFunction.MAX)))); sr = response.actionGet(); sh = sr.getHits(); assertThat(sh.getTotalHits(), equalTo((long) (1))); assertThat(sh.getAt(0).getId(), equalTo("1")); assertThat((double) sh.getAt(0).getScore(), closeTo(2.0, 1.e-5)); }
/** * A query that allows to define a custom scoring function. */ public static FunctionScoreQueryBuilder functionScoreQuery() { return new FunctionScoreQueryBuilder(); }
public void testFunctionScore() { SearchRequest searchRequest = searchRequest() .source(searchSource().query(new FunctionScoreQueryBuilder(matchQuery("party_id", "12")) .add(termsQuery("course_cd", Arrays.asList("writ100", "writ112", "writ113")), weightFactorFunction(3.0f)))); }
public static void main(String[] args) { final BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); final FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(boolQuery, ScoreFunctionBuilders.randomFunction(1)) .boostMode(CombineFunction.REPLACE); }
/** * A function_score query with no functions. * * @param queryBuilder The query to custom score * @return the function score query */ public static FunctionScoreQueryBuilder functionScoreQuery(QueryBuilder queryBuilder) { return new FunctionScoreQueryBuilder(queryBuilder); }
/** * A query that allows to define a custom scoring function * * @param queryBuilder The query to custom score * @param filterFunctionBuilders the filters and functions to execute * @return the function score query */ public static FunctionScoreQueryBuilder functionScoreQuery(QueryBuilder queryBuilder, FunctionScoreQueryBuilder.FilterFunctionBuilder[] filterFunctionBuilders) { return new FunctionScoreQueryBuilder(queryBuilder, filterFunctionBuilders); }
/** * A query that allows to define a custom scoring function * * @param filterFunctionBuilders the filters and functions to execute * @return the function score query */ public static FunctionScoreQueryBuilder functionScoreQuery(FunctionScoreQueryBuilder.FilterFunctionBuilder[] filterFunctionBuilders) { return new FunctionScoreQueryBuilder(filterFunctionBuilders); }
/** * A query that allows to define a custom scoring function. * * @param function The function builder used to custom score */ public static FunctionScoreQueryBuilder functionScoreQuery(ScoreFunctionBuilder function) { return new FunctionScoreQueryBuilder(function); }
/** * A query that allows to define a custom scoring function. * * @param queryBuilder The query to custom score * @param function The function builder used to custom score */ public static FunctionScoreQueryBuilder functionScoreQuery(QueryBuilder queryBuilder, ScoreFunctionBuilder function) { return (new FunctionScoreQueryBuilder(queryBuilder, function)); }
/** * A query that allows to define a custom scoring function. * * @param queryBuilder The query to custom score */ public static FunctionScoreQueryBuilder functionScoreQuery(QueryBuilder queryBuilder) { return new FunctionScoreQueryBuilder(queryBuilder); }
/** * A query that allows to define a custom scoring function. * * @param queryBuilder The query to custom score * @param function The function builder used to custom score */ public static FunctionScoreQueryBuilder functionScoreQuery(QueryBuilder queryBuilder, ScoreFunctionBuilder function) { return (new FunctionScoreQueryBuilder(queryBuilder)).add(function); }