@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(); }
public void testScore() throws Exception { createIndex("test"); ensureGreen("test"); indexRandom(true, client().prepareIndex("test", "doc", "1").setSource("text", "hello goodbye"), client().prepareIndex("test", "doc", "2").setSource("text", "hello hello hello goodbye"), client().prepareIndex("test", "doc", "3").setSource("text", "hello hello goodebye")); ScoreFunctionBuilder<?> score = ScoreFunctionBuilders.scriptFunction(new Script(ScriptType.INLINE, "expression", "1 / _score", Collections.emptyMap())); SearchRequestBuilder req = client().prepareSearch().setIndices("test"); req.setQuery(QueryBuilders.functionScoreQuery(QueryBuilders.termQuery("text", "hello"), score).boostMode(CombineFunction.REPLACE)); req.setSearchType(SearchType.DFS_QUERY_THEN_FETCH); // make sure DF is consistent SearchResponse rsp = req.get(); assertSearchResponse(rsp); SearchHits hits = rsp.getHits(); assertEquals(3, hits.getTotalHits()); assertEquals("1", hits.getAt(0).getId()); assertEquals("3", hits.getAt(1).getId()); assertEquals("2", hits.getAt(2).getId()); }
/** * 根据搜索词构造搜索查询语句 * * 代码流程: * - 权重分查询 * - 短语匹配 * - 设置权重分最小值 * - 设置分页参数 * * @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(); }
@Test public void test() throws Exception { SearchResponse searchResponse = client.prepareSearch() .setIndices("test") .setTypes("test") .setQuery(QueryBuilders.matchQuery("name","天津公安")) .addRescorer(new QueryRescorerBuilder(QueryBuilders.matchPhraseQuery("name","天津公安"))) .addRescorer(new QueryRescorerBuilder( QueryBuilders.functionScoreQuery( ScoreFunctionBuilders.scriptFunction("doc['time'].value / 10000") ) ).windowSize(100).setScoreMode(QueryRescoreMode.Multiply)) .setFrom(0) .setSize(100) .execute() .actionGet(); }
/** * * * * @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(); }
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; }
private void checkOnlyFunctionScore(Script scoreScript, Map<String, Object> expectedScore, int numExpectedDocs) { SearchResponse sr = client().prepareSearch("test") .setQuery(QueryBuilders.functionScoreQuery(ScoreFunctionBuilders.scriptFunction(scoreScript))).execute() .actionGet(); assertHitCount(sr, numExpectedDocs); for (SearchHit hit : sr.getHits().getHits()) { assertThat("for doc " + hit.getId(), ((Float) expectedScore.get(hit.getId())).doubleValue(), Matchers.closeTo(hit.getScore(), 1.e-4)); } }
private void checkValueInEachDocWithFunctionScore(Script fieldScript, Map<String, Object> expectedFieldVals, Script scoreScript, Map<String, Object> expectedScore, int numExpectedDocs) { SearchResponse sr = client().prepareSearch("test") .setQuery(QueryBuilders.functionScoreQuery(ScoreFunctionBuilders.scriptFunction(scoreScript))) .addScriptField("tvtest", fieldScript).execute().actionGet(); assertHitCount(sr, numExpectedDocs); for (SearchHit hit : sr.getHits().getHits()) { Object result = hit.getFields().get("tvtest").getValues().get(0); Object expectedResult = expectedFieldVals.get(hit.getId()); assertThat("for doc " + hit.getId(), result, equalTo(expectedResult)); assertThat("for doc " + hit.getId(), ((Float) expectedScore.get(hit.getId())).doubleValue(), Matchers.closeTo(hit.getScore(), 1.e-4)); } }
public void testEnforceWindowSize() { createIndex("test"); // this int iters = scaledRandomIntBetween(10, 20); for (int i = 0; i < iters; i ++) { client().prepareIndex("test", "type", Integer.toString(i)).setSource("f", Integer.toString(i)).execute().actionGet(); } refresh(); int numShards = getNumShards("test").numPrimaries; for (int j = 0 ; j < iters; j++) { SearchResponse searchResponse = client().prepareSearch() .setQuery(QueryBuilders.matchAllQuery()) .setRescorer(queryRescorer( QueryBuilders.functionScoreQuery(QueryBuilders.matchAllQuery(), ScoreFunctionBuilders.weightFactorFunction(100)).boostMode(CombineFunction.REPLACE)) .setQueryWeight(0.0f).setRescoreQueryWeight(1.0f), 1).setSize(randomIntBetween(2, 10)).execute() .actionGet(); assertSearchResponse(searchResponse); assertFirstHit(searchResponse, hasScore(100.f)); int numDocsWith100AsAScore = 0; for (int i = 0; i < searchResponse.getHits().getHits().length; i++) { float score = searchResponse.getHits().getHits()[i].getScore(); if (score == 100f) { numDocsWith100AsAScore += 1; } } assertThat(searchResponse.getHits().getMaxScore(), equalTo(searchResponse.getHits().getHits()[0].getScore())); // we cannot assert that they are equal since some shards might not have docs at all assertThat(numDocsWith100AsAScore, lessThanOrEqualTo(numShards)); } }
public void testMultipleRescores() throws Exception { int numDocs = indexRandomNumbers("keyword", 1, true); QueryRescorerBuilder eightIsGreat = RescoreBuilder .queryRescorer(QueryBuilders.functionScoreQuery(QueryBuilders.termQuery("field1", English.intToEnglish(8)), ScoreFunctionBuilders.weightFactorFunction(1000.0f)).boostMode(CombineFunction.REPLACE)) .setScoreMode(QueryRescoreMode.Total); QueryRescorerBuilder sevenIsBetter = RescoreBuilder .queryRescorer(QueryBuilders.functionScoreQuery(QueryBuilders.termQuery("field1", English.intToEnglish(7)), ScoreFunctionBuilders.weightFactorFunction(10000.0f)).boostMode(CombineFunction.REPLACE)) .setScoreMode(QueryRescoreMode.Total); // First set the rescore window large enough that both rescores take effect SearchRequestBuilder request = client().prepareSearch(); request.addRescorer(eightIsGreat, numDocs).addRescorer(sevenIsBetter, numDocs); SearchResponse response = request.get(); assertFirstHit(response, hasId("7")); assertSecondHit(response, hasId("8")); // Now squash the second rescore window so it never gets to see a seven response = request.setSize(1).clearRescorers().addRescorer(eightIsGreat, numDocs).addRescorer(sevenIsBetter, 1).get(); assertFirstHit(response, hasId("8")); // We have no idea what the second hit will be because we didn't get a chance to look for seven // Now use one rescore to drag the number we're looking for into the window of another QueryRescorerBuilder ninetyIsGood = RescoreBuilder.queryRescorer(QueryBuilders .functionScoreQuery(QueryBuilders.queryStringQuery("*ninety*"), ScoreFunctionBuilders.weightFactorFunction(1000.0f)) .boostMode(CombineFunction.REPLACE)).setScoreMode(QueryRescoreMode.Total); QueryRescorerBuilder oneToo = RescoreBuilder.queryRescorer(QueryBuilders .functionScoreQuery(QueryBuilders.queryStringQuery("*one*"), ScoreFunctionBuilders.weightFactorFunction(1000.0f)) .boostMode(CombineFunction.REPLACE)).setScoreMode(QueryRescoreMode.Total); request.clearRescorers().addRescorer(ninetyIsGood, numDocs).addRescorer(oneToo, 10); response = request.setSize(2).get(); assertThat(response.getHits().getMaxScore(), equalTo(response.getHits().getHits()[0].getScore())); assertFirstHit(response, hasId("91")); assertFirstHit(response, hasScore(2001.0f)); assertSecondHit(response, hasScore(1001.0f)); // Not sure which one it is but it is ninety something }
public void testMinScore() throws ExecutionException, InterruptedException { createIndex("test"); client().prepareIndex("test", "test", "1").setSource("score", 1.5).get(); client().prepareIndex("test", "test", "2").setSource("score", 1.0).get(); client().prepareIndex("test", "test", "3").setSource("score", 2.0).get(); client().prepareIndex("test", "test", "4").setSource("score", 0.5).get(); refresh(); SearchResponse searchResponse = client().prepareSearch("test").setQuery( functionScoreQuery(ScoreFunctionBuilders.fieldValueFactorFunction("score").missing(1.0)).setMinScore(1.5f)).get(); assertHitCount(searchResponse, 2); assertFirstHit(searchResponse, hasId("3")); assertSecondHit(searchResponse, hasId("1")); }
@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); }
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); }
@Override public QueryBuilderHelper scriptFunction(String functionScore) { if (functionScore != null) { this.alterQuery(query -> QueryBuilders.functionScoreQuery(query, ScoreFunctionBuilders.scriptFunction(functionScore))); } return this; }
public static QueryBuilder build(QueryBuilder childQuery, Float timeBoost) { Date minusThirtyDays = DateTime.now().minusDays(30).toDateTime(DateTimeZones.UTC).toDate(); long minusThirtyDaysMillis = minusThirtyDays.toInstant().getEpochSecond() * 1000; long nowMilis = new Date().toInstant().getEpochSecond() * 1000; return QueryBuilders.functionScoreQuery( childQuery ).add(ScoreFunctionBuilders.gaussDecayFunction( EsBroadcast.TRANSMISSION_TIME_IN_MILLIS, nowMilis, minusThirtyDaysMillis ).setMultiValueMode(MultiValueMode.MIN) ).boost(timeBoost); }
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; }
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)); }
public void testScoreSortDirection() throws Exception { createIndex("test"); ensureGreen(); client().prepareIndex("test", "type", "1").setSource("field", 2).execute().actionGet(); client().prepareIndex("test", "type", "2").setSource("field", 1).execute().actionGet(); client().prepareIndex("test", "type", "3").setSource("field", 0).execute().actionGet(); refresh(); SearchResponse searchResponse = client() .prepareSearch("test") .setQuery( QueryBuilders.functionScoreQuery(matchAllQuery(), ScoreFunctionBuilders.fieldValueFactorFunction("field"))) .execute().actionGet(); assertThat(searchResponse.getHits().getAt(0).getId(), equalTo("1")); assertThat(searchResponse.getHits().getAt(1).getScore(), Matchers.lessThan(searchResponse.getHits().getAt(0).getScore())); assertThat(searchResponse.getHits().getAt(1).getId(), equalTo("2")); assertThat(searchResponse.getHits().getAt(2).getScore(), Matchers.lessThan(searchResponse.getHits().getAt(1).getScore())); assertThat(searchResponse.getHits().getAt(2).getId(), equalTo("3")); searchResponse = client() .prepareSearch("test") .setQuery( QueryBuilders.functionScoreQuery(matchAllQuery(), ScoreFunctionBuilders.fieldValueFactorFunction("field"))) .addSort("_score", SortOrder.DESC).execute().actionGet(); assertThat(searchResponse.getHits().getAt(0).getId(), equalTo("1")); assertThat(searchResponse.getHits().getAt(1).getScore(), Matchers.lessThan(searchResponse.getHits().getAt(0).getScore())); assertThat(searchResponse.getHits().getAt(1).getId(), equalTo("2")); assertThat(searchResponse.getHits().getAt(2).getScore(), Matchers.lessThan(searchResponse.getHits().getAt(1).getScore())); assertThat(searchResponse.getHits().getAt(2).getId(), equalTo("3")); searchResponse = client() .prepareSearch("test") .setQuery( QueryBuilders.functionScoreQuery(matchAllQuery(), ScoreFunctionBuilders.fieldValueFactorFunction("field"))) .addSort("_score", SortOrder.DESC).execute().actionGet(); assertThat(searchResponse.getHits().getAt(2).getId(), equalTo("3")); assertThat(searchResponse.getHits().getAt(1).getId(), equalTo("2")); assertThat(searchResponse.getHits().getAt(0).getId(), equalTo("1")); }
public static void main(String[] args) { final BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); final FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(boolQuery, ScoreFunctionBuilders.randomFunction(1)) .boostMode(CombineFunction.REPLACE); }
protected RescorerBuilder<?> buildRescore() { return new QueryRescorerBuilder(QueryBuilders.functionScoreQuery(ScoreFunctionBuilders.randomFunction().seed(seed).setField("_id"))) .setQueryWeight(0).setRescoreQueryWeight(1); }