diff --git a/src/main/java/org/elasticsearch/index/query/CustomBoostFactorQueryBuilder.java b/src/main/java/org/elasticsearch/index/query/CustomBoostFactorQueryBuilder.java deleted file mode 100644 index 392b8f1d313..00000000000 --- a/src/main/java/org/elasticsearch/index/query/CustomBoostFactorQueryBuilder.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder; - -import java.io.IOException; - -/** - * A query that simply applies the boost factor to another query (multiply it). - * - * @deprecated use {@link FunctionScoreQueryBuilder} instead. - */ -public class CustomBoostFactorQueryBuilder extends BaseQueryBuilder { - - private final QueryBuilder queryBuilder; - - private float boostFactor = -1; - - /** - * A query that simply applies the boost factor to another query (multiply - * it). - * - * @param queryBuilder - * The query to apply the boost factor to. - */ - public CustomBoostFactorQueryBuilder(QueryBuilder queryBuilder) { - this.queryBuilder = queryBuilder; - } - - /** - * Sets the boost factor for this query. - */ - public CustomBoostFactorQueryBuilder boostFactor(float boost) { - this.boostFactor = boost; - return this; - } - - @Override - protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(CustomBoostFactorQueryParser.NAME); - builder.field("query"); - queryBuilder.toXContent(builder, params); - if (boostFactor != -1) { - builder.field("boost_factor", boostFactor); - } - builder.endObject(); - } -} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/CustomBoostFactorQueryParser.java b/src/main/java/org/elasticsearch/index/query/CustomBoostFactorQueryParser.java deleted file mode 100644 index 3a9c91651a8..00000000000 --- a/src/main/java/org/elasticsearch/index/query/CustomBoostFactorQueryParser.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.apache.lucene.search.Query; -import org.elasticsearch.common.Strings; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.lucene.search.function.BoostScoreFunction; -import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery; -import org.elasticsearch.common.xcontent.XContentParser; -import org.elasticsearch.index.query.functionscore.FunctionScoreQueryParser; - -import java.io.IOException; - -/** - * @deprecated use {@link FunctionScoreQueryParser} instead. - */ -public class CustomBoostFactorQueryParser implements QueryParser { - - public static final String NAME = "custom_boost_factor"; - - @Inject - public CustomBoostFactorQueryParser() { - } - - @Override - public String[] names() { - return new String[] { NAME, Strings.toCamelCase(NAME) }; - } - - @Override - public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { - XContentParser parser = parseContext.parser(); - - Query query = null; - boolean queryFound = false; - float boost = 1.0f; - float boostFactor = 1.0f; - - String currentFieldName = null; - XContentParser.Token token; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (token == XContentParser.Token.START_OBJECT) { - if ("query".equals(currentFieldName)) { - query = parseContext.parseInnerQuery(); - queryFound = true; - } else { - throw new QueryParsingException(parseContext.index(), "[custom_boost_factor] query does not support [" - + currentFieldName + "]"); - } - } else if (token.isValue()) { - if ("boost_factor".equals(currentFieldName) || "boostFactor".equals(currentFieldName)) { - boostFactor = parser.floatValue(); - } else if ("boost".equals(currentFieldName)) { - boost = parser.floatValue(); - } else { - throw new QueryParsingException(parseContext.index(), "[custom_boost_factor] query does not support [" - + currentFieldName + "]"); - } - } - } - if (!queryFound) { - throw new QueryParsingException(parseContext.index(), "[constant_factor_query] requires 'query' element"); - } - if (query == null) { - return null; - } - FunctionScoreQuery functionScoreQuery = new FunctionScoreQuery(query, new BoostScoreFunction(boostFactor)); - functionScoreQuery.setBoost(boost); - return functionScoreQuery; - } -} diff --git a/src/main/java/org/elasticsearch/index/query/CustomFiltersScoreQueryBuilder.java b/src/main/java/org/elasticsearch/index/query/CustomFiltersScoreQueryBuilder.java deleted file mode 100644 index 4c3872b1d6e..00000000000 --- a/src/main/java/org/elasticsearch/index/query/CustomFiltersScoreQueryBuilder.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import com.carrotsearch.hppc.FloatArrayList; -import com.google.common.collect.Maps; -import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Map; - -/** - * A query that uses a filters with a script associated with them to compute the - * score. - * - * @deprecated use {@link FunctionScoreQueryBuilder} instead. - */ -public class CustomFiltersScoreQueryBuilder extends BaseQueryBuilder implements BoostableQueryBuilder { - - private final QueryBuilder queryBuilder; - - private String lang; - - private float boost = -1; - - private Float maxBoost; - - private Map params = null; - - private String scoreMode; - - private ArrayList filters = new ArrayList(); - private ArrayList scripts = new ArrayList(); - private FloatArrayList boosts = new FloatArrayList(); - - public CustomFiltersScoreQueryBuilder(QueryBuilder queryBuilder) { - this.queryBuilder = queryBuilder; - } - - public CustomFiltersScoreQueryBuilder add(FilterBuilder filter, String script) { - this.filters.add(filter); - this.scripts.add(script); - this.boosts.add(-1); - return this; - } - - public CustomFiltersScoreQueryBuilder add(FilterBuilder filter, float boost) { - this.filters.add(filter); - this.scripts.add(null); - this.boosts.add(boost); - return this; - } - - public CustomFiltersScoreQueryBuilder scoreMode(String scoreMode) { - this.scoreMode = scoreMode; - return this; - } - - /** - * Sets the language of the script. - */ - public CustomFiltersScoreQueryBuilder lang(String lang) { - this.lang = lang; - return this; - } - - /** - * Additional parameters that can be provided to the script. - */ - public CustomFiltersScoreQueryBuilder params(Map params) { - if (this.params == null) { - this.params = params; - } else { - this.params.putAll(params); - } - return this; - } - - /** - * Additional parameters that can be provided to the script. - */ - public CustomFiltersScoreQueryBuilder param(String key, Object value) { - if (params == null) { - params = Maps.newHashMap(); - } - params.put(key, value); - return this; - } - - public CustomFiltersScoreQueryBuilder maxBoost(float maxBoost) { - this.maxBoost = maxBoost; - return this; - } - - /** - * Sets the boost for this query. Documents matching this query will (in - * addition to the normal weightings) have their score multiplied by the - * boost provided. - */ - public CustomFiltersScoreQueryBuilder boost(float boost) { - this.boost = boost; - return this; - } - - @Override - protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(CustomFiltersScoreQueryParser.NAME); - builder.field("query"); - queryBuilder.toXContent(builder, params); - - builder.startArray("filters"); - for (int i = 0; i < filters.size(); i++) { - builder.startObject(); - builder.field("filter"); - filters.get(i).toXContent(builder, params); - String script = scripts.get(i); - if (script != null) { - builder.field("script", script); - } else { - builder.field("boost", boosts.get(i)); - } - builder.endObject(); - } - builder.endArray(); - - if (scoreMode != null) { - builder.field("score_mode", scoreMode); - } - if (maxBoost != null) { - builder.field("max_boost", maxBoost); - } - - if (lang != null) { - builder.field("lang", lang); - } - if (this.params != null) { - builder.field("params", this.params); - } - if (boost != -1) { - builder.field("boost", boost); - } - builder.endObject(); - } -} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/CustomFiltersScoreQueryParser.java b/src/main/java/org/elasticsearch/index/query/CustomFiltersScoreQueryParser.java deleted file mode 100644 index 9e61f5ecaf2..00000000000 --- a/src/main/java/org/elasticsearch/index/query/CustomFiltersScoreQueryParser.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import com.carrotsearch.hppc.FloatArrayList; -import org.apache.lucene.search.Filter; -import org.apache.lucene.search.Query; -import org.elasticsearch.common.Strings; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.lucene.search.function.BoostScoreFunction; -import org.elasticsearch.common.lucene.search.function.FiltersFunctionScoreQuery; -import org.elasticsearch.common.lucene.search.function.ScoreFunction; -import org.elasticsearch.common.lucene.search.function.ScriptScoreFunction; -import org.elasticsearch.common.xcontent.XContentParser; -import org.elasticsearch.index.query.functionscore.FunctionScoreQueryParser; -import org.elasticsearch.script.SearchScript; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Map; - -/** - * @deprecated use {@link FunctionScoreQueryParser} instead. - */ -public class CustomFiltersScoreQueryParser implements QueryParser { - - public static final String NAME = "custom_filters_score"; - - @Inject - public CustomFiltersScoreQueryParser() { - } - - @Override - public String[] names() { - return new String[] { NAME, Strings.toCamelCase(NAME) }; - } - - @Override - public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { - XContentParser parser = parseContext.parser(); - - Query query = null; - boolean queryFound = false; - float boost = 1.0f; - String scriptLang = null; - Map vars = null; - - FiltersFunctionScoreQuery.ScoreMode scoreMode = FiltersFunctionScoreQuery.ScoreMode.First; - ArrayList filters = new ArrayList(); - boolean filtersFound = false; - ArrayList scripts = new ArrayList(); - FloatArrayList boosts = new FloatArrayList(); - float maxBoost = Float.MAX_VALUE; - - String currentFieldName = null; - XContentParser.Token token; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (token == XContentParser.Token.START_OBJECT) { - if ("query".equals(currentFieldName)) { - query = parseContext.parseInnerQuery(); - queryFound = true; - } else if ("params".equals(currentFieldName)) { - vars = parser.map(); - } else { - throw new QueryParsingException(parseContext.index(), "[custom_filters_score] query does not support [" - + currentFieldName + "]"); - } - } else if (token == XContentParser.Token.START_ARRAY) { - if ("filters".equals(currentFieldName)) { - filtersFound = true; - while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { - String script = null; - Filter filter = null; - boolean filterFound = false; - float fboost = Float.NaN; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (token == XContentParser.Token.START_OBJECT) { - if ("filter".equals(currentFieldName)) { - filter = parseContext.parseInnerFilter(); - filterFound = true; - } - } else if (token.isValue()) { - if ("script".equals(currentFieldName)) { - script = parser.text(); - } else if ("boost".equals(currentFieldName)) { - fboost = parser.floatValue(); - } - } - } - if (script == null && fboost == -1) { - throw new QueryParsingException(parseContext.index(), - "[custom_filters_score] missing 'script' or 'boost' in filters array element"); - } - if (!filterFound) { - throw new QueryParsingException(parseContext.index(), - "[custom_filters_score] missing 'filter' in filters array element"); - } - if (filter != null) { - filters.add(filter); - scripts.add(script); - boosts.add(fboost); - } - } - } else { - throw new QueryParsingException(parseContext.index(), "[custom_filters_score] query does not support [" - + currentFieldName + "]"); - } - } else if (token.isValue()) { - if ("lang".equals(currentFieldName)) { - scriptLang = parser.text(); - } else if ("boost".equals(currentFieldName)) { - boost = parser.floatValue(); - } else if ("score_mode".equals(currentFieldName) || "scoreMode".equals(currentFieldName)) { - String sScoreMode = parser.text(); - if ("avg".equals(sScoreMode)) { - scoreMode = FiltersFunctionScoreQuery.ScoreMode.Avg; - } else if ("max".equals(sScoreMode)) { - scoreMode = FiltersFunctionScoreQuery.ScoreMode.Max; - } else if ("min".equals(sScoreMode)) { - scoreMode = FiltersFunctionScoreQuery.ScoreMode.Min; - } else if ("total".equals(sScoreMode)) { - scoreMode = FiltersFunctionScoreQuery.ScoreMode.Sum; - } else if ("multiply".equals(sScoreMode)) { - scoreMode = FiltersFunctionScoreQuery.ScoreMode.Multiply; - } else if ("first".equals(sScoreMode)) { - scoreMode = FiltersFunctionScoreQuery.ScoreMode.First; - } else { - throw new QueryParsingException(parseContext.index(), "[custom_filters_score] illegal score_mode [" + sScoreMode - + "]"); - } - } else if ("max_boost".equals(currentFieldName) || "maxBoost".equals(currentFieldName)) { - maxBoost = parser.floatValue(); - } else { - throw new QueryParsingException(parseContext.index(), "[custom_filters_score] query does not support [" - + currentFieldName + "]"); - } - } - } - if (!queryFound) { - throw new QueryParsingException(parseContext.index(), "[custom_filters_score] requires 'query' field"); - } - if (query == null) { - return null; - } - if (!filtersFound) { - throw new QueryParsingException(parseContext.index(), "[custom_filters_score] requires 'filters' field"); - } - // if all filter elements returned null, just use the query - if (filters.isEmpty()) { - return query; - } - - FiltersFunctionScoreQuery.FilterFunction[] filterFunctions = new FiltersFunctionScoreQuery.FilterFunction[filters.size()]; - for (int i = 0; i < filterFunctions.length; i++) { - ScoreFunction scoreFunction; - String script = scripts.get(i); - if (script != null) { - SearchScript searchScript = parseContext.scriptService().search(parseContext.lookup(), scriptLang, script, vars); - scoreFunction = new ScriptScoreFunction(script, vars, searchScript); - } else { - scoreFunction = new BoostScoreFunction(boosts.get(i)); - } - filterFunctions[i] = new FiltersFunctionScoreQuery.FilterFunction(filters.get(i), scoreFunction); - } - FiltersFunctionScoreQuery functionScoreQuery = new FiltersFunctionScoreQuery(query, scoreMode, filterFunctions, maxBoost); - functionScoreQuery.setBoost(boost); - return functionScoreQuery; - } -} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/CustomScoreQueryBuilder.java b/src/main/java/org/elasticsearch/index/query/CustomScoreQueryBuilder.java deleted file mode 100644 index dd3d0b9444b..00000000000 --- a/src/main/java/org/elasticsearch/index/query/CustomScoreQueryBuilder.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import com.google.common.collect.Maps; -import org.elasticsearch.common.xcontent.XContentBuilder; - -import java.io.IOException; -import java.util.Map; - -/** - * A query that uses a script to compute or influence the score of documents - * that match with the inner query or filter. - * - * @deprecated use {@link FunctionScoreQueryBuilder} instead. - */ -public class CustomScoreQueryBuilder extends BaseQueryBuilder implements BoostableQueryBuilder { - - private final QueryBuilder queryBuilder; - - private final FilterBuilder filterBuilder; - - private String script; - - private String lang; - - private float boost = -1; - - private Map params = null; - - /** - * Constructs a query that defines how the scores are computed or influenced - * for documents that match with the specified query by a custom defined - * script. - * - * @param queryBuilder - * The query that defines what documents are custom scored by - * this query - */ - public CustomScoreQueryBuilder(QueryBuilder queryBuilder) { - this.queryBuilder = queryBuilder; - this.filterBuilder = null; - } - - /** - * Constructs a query that defines how documents are scored that match with - * the specified filter. - * - * @param filterBuilder - * The filter that decides with documents are scored by this - * query. - */ - public CustomScoreQueryBuilder(FilterBuilder filterBuilder) { - this.filterBuilder = filterBuilder; - this.queryBuilder = null; - } - - /** - * Sets the boost factor for this query. - */ - public CustomScoreQueryBuilder script(String script) { - this.script = script; - return this; - } - - /** - * Sets the language of the script. - */ - public CustomScoreQueryBuilder lang(String lang) { - this.lang = lang; - return this; - } - - /** - * Additional parameters that can be provided to the script. - */ - public CustomScoreQueryBuilder params(Map params) { - if (this.params == null) { - this.params = params; - } else { - this.params.putAll(params); - } - return this; - } - - /** - * Additional parameters that can be provided to the script. - */ - public CustomScoreQueryBuilder param(String key, Object value) { - if (params == null) { - params = Maps.newHashMap(); - } - params.put(key, value); - return this; - } - - /** - * Sets the boost for this query. Documents matching this query will (in - * addition to the normal weightings) have their score multiplied by the - * boost provided. - */ - public CustomScoreQueryBuilder boost(float boost) { - this.boost = boost; - return this; - } - - @Override - protected void doXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(CustomScoreQueryParser.NAME); - if (queryBuilder != null) { - builder.field("query"); - queryBuilder.toXContent(builder, params); - } else if (filterBuilder != null) { - builder.field("filter"); - filterBuilder.toXContent(builder, params); - } - builder.field("script", script); - if (lang != null) { - builder.field("lang", lang); - } - if (this.params != null) { - builder.field("params", this.params); - } - if (boost != -1) { - builder.field("boost", boost); - } - builder.endObject(); - } -} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/CustomScoreQueryParser.java b/src/main/java/org/elasticsearch/index/query/CustomScoreQueryParser.java deleted file mode 100644 index 5a1363bf187..00000000000 --- a/src/main/java/org/elasticsearch/index/query/CustomScoreQueryParser.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.index.query; - -import org.apache.lucene.search.Filter; -import org.apache.lucene.search.Query; -import org.elasticsearch.common.Strings; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.lucene.search.XConstantScoreQuery; -import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery; -import org.elasticsearch.common.lucene.search.function.ScriptScoreFunction; -import org.elasticsearch.common.xcontent.XContentParser; -import org.elasticsearch.script.SearchScript; - -import java.io.IOException; -import java.util.Map; - -/** - * @deprecated use {@link FunctionScoreQueryParser} instead. - */ -public class CustomScoreQueryParser implements QueryParser { - - public static final String NAME = "custom_score"; - - @Inject - public CustomScoreQueryParser() { - } - - @Override - public String[] names() { - return new String[] { NAME, Strings.toCamelCase(NAME) }; - } - - @Override - public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { - XContentParser parser = parseContext.parser(); - - Query query = null; - Filter filter = null; - boolean queryOrFilterFound = false; - float boost = 1.0f; - String script = null; - String scriptLang = null; - Map vars = null; - - String currentFieldName = null; - XContentParser.Token token; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (token == XContentParser.Token.START_OBJECT) { - if ("query".equals(currentFieldName)) { - query = parseContext.parseInnerQuery(); - queryOrFilterFound = true; - } else if ("filter".equals(currentFieldName)) { - filter = parseContext.parseInnerFilter(); - queryOrFilterFound = true; - } else if ("params".equals(currentFieldName)) { - vars = parser.map(); - } else { - throw new QueryParsingException(parseContext.index(), "[custom_score] query does not support [" + currentFieldName - + "]"); - } - } else if (token.isValue()) { - if ("script".equals(currentFieldName)) { - script = parser.text(); - } else if ("lang".equals(currentFieldName)) { - scriptLang = parser.text(); - } else if ("boost".equals(currentFieldName)) { - boost = parser.floatValue(); - } else { - throw new QueryParsingException(parseContext.index(), "[custom_score] query does not support [" + currentFieldName - + "]"); - } - } - } - if (!queryOrFilterFound) { - throw new QueryParsingException(parseContext.index(), "[custom_score] requires 'query' or 'filter' field"); - } - if (script == null) { - throw new QueryParsingException(parseContext.index(), "[custom_score] requires 'script' field"); - } - if (query == null && filter == null) { - return null; - } else if (filter != null) { - query = new XConstantScoreQuery(filter); - } - - SearchScript searchScript; - try { - searchScript = parseContext.scriptService().search(parseContext.lookup(), scriptLang, script, vars); - } catch (Exception e) { - throw new QueryParsingException(parseContext.index(), "[custom_score] the script could not be loaded", e); - } - FunctionScoreQuery functionScoreQuery = new FunctionScoreQuery(query, new ScriptScoreFunction(script, vars, searchScript)); - functionScoreQuery.setBoost(boost); - return functionScoreQuery; - } -} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/query/QueryBuilders.java b/src/main/java/org/elasticsearch/index/query/QueryBuilders.java index e63f9da07ac..cddd730cfd7 100644 --- a/src/main/java/org/elasticsearch/index/query/QueryBuilders.java +++ b/src/main/java/org/elasticsearch/index/query/QueryBuilders.java @@ -419,44 +419,6 @@ public abstract class QueryBuilders { return new ConstantScoreQueryBuilder(queryBuilder); } - /** - * A query that simply applies the boost fact to the wrapped query (multiplies it). - * - * @param queryBuilder The query to apply the boost factor to. - * @deprecated use {@link #functionScoreQuery(QueryBuilder)} instead - */ - public static CustomBoostFactorQueryBuilder customBoostFactorQuery(QueryBuilder queryBuilder) { - return new CustomBoostFactorQueryBuilder(queryBuilder); - } - - /** - * A query that allows to define a custom scoring script. - * - * @param queryBuilder The query to custom score - * @deprecated use {@link #functionScoreQuery(QueryBuilder)} instead - */ - public static CustomScoreQueryBuilder customScoreQuery(QueryBuilder queryBuilder) { - return new CustomScoreQueryBuilder(queryBuilder); - } - - /** - * A query that allows to define a custom scoring script, that defines the score for each document that match - * with the specified filter. - * - * @param filterBuilder The filter that defines which documents are scored by a script. - * @deprecated use {@link #functionScoreQuery(QueryBuilder)} instead - */ - public static CustomScoreQueryBuilder customScoreQuery(FilterBuilder filterBuilder) { - return new CustomScoreQueryBuilder(filterBuilder); - } - - /** - * @deprecated use {@link #functionScoreQuery(QueryBuilder)} instead - */ - public static CustomFiltersScoreQueryBuilder customFiltersScoreQuery(QueryBuilder queryBuilder) { - return new CustomFiltersScoreQueryBuilder(queryBuilder); - } - /** * A query that allows to define a custom scoring function. * diff --git a/src/main/java/org/elasticsearch/indices/query/IndicesQueriesModule.java b/src/main/java/org/elasticsearch/indices/query/IndicesQueriesModule.java index d616c901894..da7029f6ea3 100644 --- a/src/main/java/org/elasticsearch/indices/query/IndicesQueriesModule.java +++ b/src/main/java/org/elasticsearch/indices/query/IndicesQueriesModule.java @@ -87,9 +87,6 @@ public class IndicesQueriesModule extends AbstractModule { qpBinders.addBinding().to(WildcardQueryParser.class).asEagerSingleton(); qpBinders.addBinding().to(FilteredQueryParser.class).asEagerSingleton(); qpBinders.addBinding().to(ConstantScoreQueryParser.class).asEagerSingleton(); - qpBinders.addBinding().to(CustomBoostFactorQueryParser.class).asEagerSingleton(); - qpBinders.addBinding().to(CustomScoreQueryParser.class).asEagerSingleton(); - qpBinders.addBinding().to(CustomFiltersScoreQueryParser.class).asEagerSingleton(); qpBinders.addBinding().to(SpanTermQueryParser.class).asEagerSingleton(); qpBinders.addBinding().to(SpanNotQueryParser.class).asEagerSingleton(); qpBinders.addBinding().to(FieldMaskingSpanQueryParser.class).asEagerSingleton(); diff --git a/src/test/java/org/elasticsearch/index/query/SimpleIndexQueryParserTests.java b/src/test/java/org/elasticsearch/index/query/SimpleIndexQueryParserTests.java index eb6468036d2..18e76cb9ed9 100644 --- a/src/test/java/org/elasticsearch/index/query/SimpleIndexQueryParserTests.java +++ b/src/test/java/org/elasticsearch/index/query/SimpleIndexQueryParserTests.java @@ -1366,16 +1366,6 @@ public class SimpleIndexQueryParserTests extends ElasticsearchTestCase { // assertThat(functionScoreQuery.getFunction(), instanceOf(CustomScoreQueryParser.ScriptScoreFunction.class)); // } - @Test - public void testCustomBoostFactorQueryBuilder() throws IOException { - IndexQueryParserService queryParser = queryParser(); - Query parsedQuery = queryParser.parse(customBoostFactorQuery(termQuery("name.last", "banon")).boostFactor(1.3f)).query(); - assertThat(parsedQuery, instanceOf(FunctionScoreQuery.class)); - FunctionScoreQuery functionScoreQuery = (FunctionScoreQuery) parsedQuery; - assertThat(((TermQuery) functionScoreQuery.getSubQuery()).getTerm(), equalTo(new Term("name.last", "banon"))); - assertThat((double) ((BoostScoreFunction) functionScoreQuery.getFunction()).getBoost(), closeTo(1.3, 0.001)); - } - @Test public void testCustomBoostFactorQueryBuilder_withFunctionScore() throws IOException { @@ -1398,18 +1388,6 @@ public class SimpleIndexQueryParserTests extends ElasticsearchTestCase { assertThat((double) ((BoostScoreFunction) functionScoreQuery.getFunction()).getBoost(), closeTo(1.3, 0.001)); } - - @Test - public void testCustomBoostFactorQuery() throws IOException { - IndexQueryParserService queryParser = queryParser(); - String query = copyToStringFromClasspath("/org/elasticsearch/index/query/custom-boost-factor-query.json"); - Query parsedQuery = queryParser.parse(query).query(); - assertThat(parsedQuery, instanceOf(FunctionScoreQuery.class)); - FunctionScoreQuery functionScoreQuery = (FunctionScoreQuery) parsedQuery; - assertThat(((TermQuery) functionScoreQuery.getSubQuery()).getTerm(), equalTo(new Term("name.last", "banon"))); - assertThat((double) ((BoostScoreFunction) functionScoreQuery.getFunction()).getBoost(), closeTo(1.3, 0.001)); - } - @Test public void testSpanTermQueryBuilder() throws IOException { IndexQueryParserService queryParser = queryParser(); diff --git a/src/test/java/org/elasticsearch/index/query/custom-boost-factor-query.json b/src/test/java/org/elasticsearch/index/query/custom-boost-factor-query.json deleted file mode 100644 index 6f829212fc9..00000000000 --- a/src/test/java/org/elasticsearch/index/query/custom-boost-factor-query.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "custom_boost_factor":{ - "query":{ - "term":{ - "name.last":"banon" - } - }, - "boost_factor":1.3 - } -} \ No newline at end of file diff --git a/src/test/java/org/elasticsearch/index/query/custom_score1.json b/src/test/java/org/elasticsearch/index/query/custom_score1.json deleted file mode 100644 index 6d7dcac1e61..00000000000 --- a/src/test/java/org/elasticsearch/index/query/custom_score1.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "custom_score":{ - "query":{ - "term":{ - "name.last":"banon" - } - }, - "script":"score * doc['name.first']" - } -} \ No newline at end of file diff --git a/src/test/java/org/elasticsearch/search/basic/TransportTwoNodesSearchTests.java b/src/test/java/org/elasticsearch/search/basic/TransportTwoNodesSearchTests.java index 16b8b2eea58..d8bae15b05d 100644 --- a/src/test/java/org/elasticsearch/search/basic/TransportTwoNodesSearchTests.java +++ b/src/test/java/org/elasticsearch/search/basic/TransportTwoNodesSearchTests.java @@ -109,10 +109,8 @@ public class TransportTwoNodesSearchTests extends ElasticsearchIntegrationTest { assertThat(searchResponse.getHits().totalHits(), equalTo(100l)); assertThat(searchResponse.getHits().hits().length, equalTo(60)); -// System.out.println("max_score: " + searchResponse.hits().maxScore()); for (int i = 0; i < 60; i++) { SearchHit hit = searchResponse.getHits().hits()[i]; -// System.out.println(hit.shard() + ": " + hit.score() + ":" + hit.explanation()); assertThat(hit.explanation(), notNullValue()); assertThat("id[" + hit.id() + "]", hit.id(), equalTo(Integer.toString(100 - i - 1))); } @@ -141,7 +139,6 @@ public class TransportTwoNodesSearchTests extends ElasticsearchIntegrationTest { assertThat(searchResponse.getHits().hits().length, equalTo(60)); for (int i = 0; i < 60; i++) { SearchHit hit = searchResponse.getHits().hits()[i]; -// System.out.println(hit.shard() + ": " + hit.explanation()); assertThat(hit.explanation(), notNullValue()); assertThat("id[" + hit.id() + "]", hit.id(), equalTo(Integer.toString(i))); } @@ -171,7 +168,6 @@ public class TransportTwoNodesSearchTests extends ElasticsearchIntegrationTest { assertThat(searchResponse.getHits().hits().length, equalTo(60)); for (int i = 0; i < 60; i++) { SearchHit hit = searchResponse.getHits().hits()[i]; -// System.out.println(hit.shard() + ": " + hit.explanation()); assertThat(hit.explanation(), notNullValue()); assertThat("id[" + hit.id() + "]", hit.id(), equalTo(Integer.toString(100 - i - 1))); } @@ -395,8 +391,8 @@ public class TransportTwoNodesSearchTests extends ElasticsearchIntegrationTest { logger.info("Start Testing failed multi search with a wrong query"); MultiSearchResponse response = client().prepareMultiSearch() - // Add custom score query with missing script - .add(client().prepareSearch("test").setQuery(QueryBuilders.customScoreQuery(QueryBuilders.termQuery("nid", 1)))) + // Add function score with a bogus score mode + .add(client().prepareSearch("test").setQuery(QueryBuilders.functionScoreQuery(QueryBuilders.termQuery("nid", 1)).scoreMode("foobar"))) .add(client().prepareSearch("test").setQuery(QueryBuilders.termQuery("nid", 2))) .add(client().prepareSearch("test").setQuery(QueryBuilders.matchAllQuery())) .execute().actionGet(); diff --git a/src/test/java/org/elasticsearch/search/child/SimpleChildQuerySearchTests.java b/src/test/java/org/elasticsearch/search/child/SimpleChildQuerySearchTests.java index 3322c7adb57..d10e4424c99 100644 --- a/src/test/java/org/elasticsearch/search/child/SimpleChildQuerySearchTests.java +++ b/src/test/java/org/elasticsearch/search/child/SimpleChildQuerySearchTests.java @@ -36,6 +36,7 @@ import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.index.mapper.MergeMappingException; import org.elasticsearch.index.query.*; +import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders; import org.elasticsearch.index.search.child.ScoreType; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.facet.terms.TermsFacet; @@ -1003,97 +1004,6 @@ public class SimpleChildQuerySearchTests extends ElasticsearchIntegrationTest { assertThat(explainResponse.getExplanation().getDescription(), equalTo("not implemented yet...")); } - @Test - public void testScoreForParentChildQueries() throws Exception { - - client().admin() - .indices() - .prepareCreate("test") - .addMapping( - "child", - jsonBuilder().startObject().startObject("child").startObject("_parent").field("type", "parent").endObject() - .endObject().endObject()) - .addMapping( - "child1", - jsonBuilder().startObject().startObject("child1").startObject("_parent").field("type", "parent").endObject() - .endObject().endObject()) - .setSettings(ImmutableSettings.settingsBuilder().put("index.number_of_shards", 2).put("index.number_of_replicas", 0)) - .execute().actionGet(); - client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().execute().actionGet(); - - indexRandom(false, createDocBuilders().toArray(new IndexRequestBuilder[0])); - refresh(); - - SearchResponse response = client() - .prepareSearch("test") - .setQuery( - QueryBuilders.hasChildQuery("child", - QueryBuilders.customScoreQuery(matchQuery("c_field2", 0)).script("doc['c_field1'].value")).scoreType("sum")) - .execute().actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(3l)); - assertThat(response.getHits().hits()[0].id(), equalTo("1")); - assertThat(response.getHits().hits()[0].score(), equalTo(6f)); - assertThat(response.getHits().hits()[1].id(), equalTo("3")); - assertThat(response.getHits().hits()[1].score(), equalTo(4f)); - assertThat(response.getHits().hits()[2].id(), equalTo("2")); - assertThat(response.getHits().hits()[2].score(), equalTo(3f)); - - response = client() - .prepareSearch("test") - .setQuery( - QueryBuilders.hasChildQuery("child", - QueryBuilders.customScoreQuery(matchQuery("c_field2", 0)).script("doc['c_field1'].value")).scoreType("max")) - .execute().actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(3l)); - assertThat(response.getHits().hits()[0].id(), equalTo("3")); - assertThat(response.getHits().hits()[0].score(), equalTo(4f)); - assertThat(response.getHits().hits()[1].id(), equalTo("2")); - assertThat(response.getHits().hits()[1].score(), equalTo(3f)); - assertThat(response.getHits().hits()[2].id(), equalTo("1")); - assertThat(response.getHits().hits()[2].score(), equalTo(2f)); - - response = client() - .prepareSearch("test") - .setQuery( - QueryBuilders.hasChildQuery("child", - QueryBuilders.customScoreQuery(matchQuery("c_field2", 0)).script("doc['c_field1'].value")).scoreType("avg")) - .execute().actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(3l)); - assertThat(response.getHits().hits()[0].id(), equalTo("3")); - assertThat(response.getHits().hits()[0].score(), equalTo(4f)); - assertThat(response.getHits().hits()[1].id(), equalTo("2")); - assertThat(response.getHits().hits()[1].score(), equalTo(3f)); - assertThat(response.getHits().hits()[2].id(), equalTo("1")); - assertThat(response.getHits().hits()[2].score(), equalTo(1.5f)); - - response = client() - .prepareSearch("test") - .setQuery( - QueryBuilders.hasParentQuery("parent", - QueryBuilders.customScoreQuery(matchQuery("p_field1", "p_value3")).script("doc['p_field2'].value")) - .scoreType("score")).addSort(SortBuilders.fieldSort("c_field3")).addSort(SortBuilders.scoreSort()) - .execute().actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(7l)); - assertThat(response.getHits().hits()[0].id(), equalTo("13")); - assertThat(response.getHits().hits()[0].score(), equalTo(5f)); - assertThat(response.getHits().hits()[1].id(), equalTo("14")); - assertThat(response.getHits().hits()[1].score(), equalTo(5f)); - assertThat(response.getHits().hits()[2].id(), equalTo("15")); - assertThat(response.getHits().hits()[2].score(), equalTo(5f)); - assertThat(response.getHits().hits()[3].id(), equalTo("16")); - assertThat(response.getHits().hits()[3].score(), equalTo(5f)); - assertThat(response.getHits().hits()[4].id(), equalTo("17")); - assertThat(response.getHits().hits()[4].score(), equalTo(5f)); - assertThat(response.getHits().hits()[5].id(), equalTo("18")); - assertThat(response.getHits().hits()[5].score(), equalTo(5f)); - assertThat(response.getHits().hits()[6].id(), equalTo("1")); - assertThat(response.getHits().hits()[6].score(), equalTo(5f)); - } - List createDocBuilders() { List indexBuilders = new ArrayList(); // Parent 1 and its children diff --git a/src/test/java/org/elasticsearch/search/customscore/CustomScoreSearchTests.java b/src/test/java/org/elasticsearch/search/customscore/CustomScoreSearchTests.java deleted file mode 100644 index e1ea9e00620..00000000000 --- a/src/test/java/org/elasticsearch/search/customscore/CustomScoreSearchTests.java +++ /dev/null @@ -1,1048 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.search.customscore; - -import org.apache.lucene.search.Explanation; -import org.elasticsearch.ElasticsearchException; -import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; -import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.action.search.SearchType; -import org.elasticsearch.common.Priority; -import org.elasticsearch.index.query.FilterBuilders; -import org.elasticsearch.test.ElasticsearchIntegrationTest; -import org.junit.Test; - -import java.io.IOException; -import java.util.Arrays; - -import static org.elasticsearch.client.Requests.*; -import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; -import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.FilterBuilders.termFilter; -import static org.elasticsearch.index.query.QueryBuilders.*; -import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.factorFunction; -import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.scriptFunction; -import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; -import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures; -import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchHits; -import static org.hamcrest.Matchers.anyOf; -import static org.hamcrest.Matchers.equalTo; - -/** - * - */ -public class CustomScoreSearchTests extends ElasticsearchIntegrationTest { - - @Test - public void testScoreExplainBug_2283() throws Exception { - client().admin().indices().prepareCreate("test").setSettings(settingsBuilder().put("index.number_of_shards", 1)).execute() - .actionGet(); - ClusterHealthResponse healthResponse = client().admin().cluster().prepareHealth("test").setWaitForYellowStatus().execute() - .actionGet(); - assertThat(healthResponse.isTimedOut(), equalTo(false)); - - client().prepareIndex("test", "type", "1").setSource("field", "value1", "color", "red").execute().actionGet(); - client().prepareIndex("test", "type", "2").setSource("field", "value2", "color", "blue").execute().actionGet(); - client().prepareIndex("test", "type", "3").setSource("field", "value3", "color", "red").execute().actionGet(); - client().prepareIndex("test", "type", "4").setSource("field", "value4", "color", "blue").execute().actionGet(); - - client().admin().indices().prepareRefresh().execute().actionGet(); - - SearchResponse searchResponse = client() - .prepareSearch("test") - .setQuery( - customFiltersScoreQuery(matchAllQuery()).add(termFilter("field", "value4"), "2") - .add(termFilter("field", "value2"), "3").scoreMode("first")).setExplain(true).execute().actionGet(); - - assertNoFailures(searchResponse); - - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), equalTo("2")); - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(3.0f)); - logger.info("--> Hit[0] {} Explanation:\n {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0) - .explanation()); - Explanation explanation = searchResponse.getHits().getAt(0).explanation(); - assertNotNull(explanation); - assertThat(explanation.isMatch(), equalTo(true)); - assertThat(explanation.getValue(), equalTo(3f)); - assertThat(explanation.getDescription(), equalTo("function score, product of:")); - - assertThat(explanation.getDetails().length, equalTo(3)); - assertThat(explanation.getDetails()[0].isMatch(), equalTo(true)); - assertThat(explanation.getDetails()[0].getValue(), equalTo(1f)); - assertThat(explanation.getDetails()[0].getDetails().length, equalTo(2)); - assertThat(explanation.getDetails()[1].isMatch(), equalTo(true)); - assertThat(explanation.getDetails()[1].getValue(), equalTo(3f)); - assertThat(explanation.getDetails()[1].getDetails().length, equalTo(2)); - - // Same query but with boost - searchResponse = client() - .prepareSearch("test") - .setQuery( - customFiltersScoreQuery(matchAllQuery()).add(termFilter("field", "value4"), "2") - .add(termFilter("field", "value2"), "3").boost(2).scoreMode("first")).setExplain(true).execute() - .actionGet(); - - assertNoFailures(searchResponse); - - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), equalTo("2")); - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(6f)); - logger.info("--> Hit[0] {} Explanation:\n {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0) - .explanation()); - explanation = searchResponse.getHits().getAt(0).explanation(); - assertNotNull(explanation); - assertThat(explanation.isMatch(), equalTo(true)); - assertThat(explanation.getValue(), equalTo(6f)); - assertThat(explanation.getDescription(), equalTo("function score, product of:")); - - assertThat(explanation.getDetails().length, equalTo(3)); - assertThat(explanation.getDetails()[0].isMatch(), equalTo(true)); - assertThat(explanation.getDetails()[0].getValue(), equalTo(1f)); - assertThat(explanation.getDetails()[0].getDetails().length, equalTo(2)); - assertThat(explanation.getDetails()[1].isMatch(), equalTo(true)); - assertThat(explanation.getDetails()[1].getValue(), equalTo(3f)); - assertThat(explanation.getDetails()[1].getDetails().length, equalTo(2)); - assertThat(explanation.getDetails()[2].getDescription(), equalTo("queryBoost")); - assertThat(explanation.getDetails()[2].getValue(), equalTo(2f)); - } - - @Test - public void testScoreExplainBug_2283_withFunctionScore() throws Exception { - client().admin().indices().prepareCreate("test").setSettings(settingsBuilder().put("index.number_of_shards", 1)).execute() - .actionGet(); - ClusterHealthResponse healthResponse = client().admin().cluster().prepareHealth("test").setWaitForYellowStatus().execute() - .actionGet(); - assertThat(healthResponse.isTimedOut(), equalTo(false)); - - client().prepareIndex("test", "type", "1").setSource("field", "value1", "color", "red").execute().actionGet(); - client().prepareIndex("test", "type", "2").setSource("field", "value2", "color", "blue").execute().actionGet(); - client().prepareIndex("test", "type", "3").setSource("field", "value3", "color", "red").execute().actionGet(); - client().prepareIndex("test", "type", "4").setSource("field", "value4", "color", "blue").execute().actionGet(); - - client().admin().indices().prepareRefresh().execute().actionGet(); - - SearchResponse searchResponse = client() - .prepareSearch("test") - .setQuery( - functionScoreQuery(matchAllQuery()).scoreMode("first").add(termFilter("field", "value4"), scriptFunction("2")) - .add(termFilter("field", "value2"), scriptFunction("3"))).setExplain(true).execute().actionGet(); - - assertThat(Arrays.toString(searchResponse.getShardFailures()), searchResponse.getFailedShards(), equalTo(0)); - - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), equalTo("2")); - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(3.0f)); - logger.info("--> Hit[0] {} Explanation:\n {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0) - .explanation()); - Explanation explanation = searchResponse.getHits().getAt(0).explanation(); - assertNotNull(explanation); - assertThat(explanation.isMatch(), equalTo(true)); - assertThat(explanation.getValue(), equalTo(3f)); - assertThat(explanation.getDescription(), equalTo("function score, product of:")); - assertThat(explanation.getDetails().length, equalTo(3)); - assertThat(explanation.getDetails()[0].isMatch(), equalTo(true)); - assertThat(explanation.getDetails()[0].getValue(), equalTo(1f)); - assertThat(explanation.getDetails()[0].getDetails().length, equalTo(2)); - assertThat(explanation.getDetails()[1].isMatch(), equalTo(true)); - assertThat(explanation.getDetails()[1].getValue(), equalTo(3f)); - assertThat(explanation.getDetails()[1].getDetails().length, equalTo(2)); - - // Same query but with boost - searchResponse = client() - .prepareSearch("test") - .setQuery( - functionScoreQuery(matchAllQuery()).scoreMode("first").add(termFilter("field", "value4"), scriptFunction("2")) - .add(termFilter("field", "value2"), scriptFunction("3")).boost(2)).setExplain(true).execute().actionGet(); - - assertThat(Arrays.toString(searchResponse.getShardFailures()), searchResponse.getFailedShards(), equalTo(0)); - - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), equalTo("2")); - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(6f)); - logger.info("--> Hit[0] {} Explanation:\n {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0) - .explanation()); - explanation = searchResponse.getHits().getAt(0).explanation(); - assertNotNull(explanation); - assertThat(explanation.isMatch(), equalTo(true)); - assertThat(explanation.getValue(), equalTo(6f)); - assertThat(explanation.getDescription(), equalTo("function score, product of:")); - - assertThat(explanation.getDetails().length, equalTo(3)); - assertThat(explanation.getDetails()[0].isMatch(), equalTo(true)); - assertThat(explanation.getDetails()[0].getValue(), equalTo(1f)); - assertThat(explanation.getDetails()[0].getDetails().length, equalTo(2)); - assertThat(explanation.getDetails()[1].isMatch(), equalTo(true)); - assertThat(explanation.getDetails()[1].getValue(), equalTo(3f)); - assertThat(explanation.getDetails()[1].getDetails().length, equalTo(2)); - assertThat(explanation.getDetails()[2].getDescription(), equalTo("queryBoost")); - assertThat(explanation.getDetails()[2].getValue(), equalTo(2f)); - } - - @Test - public void testMultiValueCustomScriptBoost() throws ElasticsearchException, IOException { - - client().admin() - .indices() - .prepareCreate("test") - .setSettings(settingsBuilder().put("index.number_of_shards", 1).put("index.number_of_replicas", 0)) - .addMapping( - "type", - jsonBuilder().startObject().startObject("type").startObject("properties").startObject("snum") - .field("type", "string").endObject().startObject("dnum").field("type", "double").endObject() - .startObject("slnum").field("type", "long").endObject().startObject("gp").field("type", "geo_point") - .endObject().endObject().endObject().endObject()).execute().actionGet(); - client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().execute().actionGet(); - - String[] values = new String[100]; - String[] gp = new String[100]; - - long[] lValues = new long[100]; - double[] dValues = new double[100]; - int offset = 1; - for (int i = 0; i < values.length; i++) { - values[i] = "" + (i + offset); - gp[i] = "" + (i + offset) + "," + (i + offset); - lValues[i] = (i + offset); - dValues[i] = (i + offset); - } - client().index( - indexRequest("test") - .type("type1") - .id("1") - .source(jsonBuilder().startObject().field("test", "value check").field("snum", values).field("dnum", dValues) - .field("lnum", lValues).field("gp", gp).endObject())).actionGet(); - offset++; - for (int i = 0; i < values.length; i++) { - values[i] = "" + (i + offset); - gp[i] = "" + (i + offset) + "," + (i + offset); - lValues[i] = (i + offset); - dValues[i] = (i + offset); - } - client().index( - indexRequest("test") - .type("type1") - .id("2") - .source(jsonBuilder().startObject().field("test", "value check").field("snum", values).field("dnum", dValues) - .field("lnum", lValues).field("gp", gp).endObject())).actionGet(); - client().admin().indices().refresh(refreshRequest()).actionGet(); - - logger.info("running min(doc['num1'].value)"); - SearchResponse response = client() - .search(searchRequest() - .searchType(SearchType.QUERY_THEN_FETCH) - .source(searchSource() - .explain(true) - .query(customScoreQuery(termQuery("test", "value")) - .script("c_min = 1000; foreach (x : doc['snum'].values) { c_min = min(Integer.parseInt(x), c_min) } return c_min")))) - .actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertThat(response.getHits().getAt(0).id(), equalTo("2")); - assertThat(response.getHits().getAt(1).id(), equalTo("1")); - - response = client().search( - searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( - searchSource().explain(true).query( - customScoreQuery(termQuery("test", "value")).script( - "c_min = 1000; foreach (x : doc['lnum'].values) { c_min = min(x, c_min) } return c_min")))) - .actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertThat(response.getHits().getAt(0).id(), equalTo("2")); - assertThat(response.getHits().getAt(1).id(), equalTo("1")); - - response = client().search( - searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( - searchSource().explain(true).query( - customScoreQuery(termQuery("test", "value")).script( - "c_min = 1000; foreach (x : doc['dnum'].values) { c_min = min(x, c_min) } return c_min")))) - .actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertThat(response.getHits().getAt(0).id(), equalTo("2")); - assertThat(response.getHits().getAt(1).id(), equalTo("1")); - - response = client().search( - searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( - searchSource().explain(true).query( - customScoreQuery(termQuery("test", "value")).script( - "c_min = 1000; foreach (x : doc['gp'].values) { c_min = min(x.lat, c_min) } return c_min")))) - .actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertThat(response.getHits().getAt(0).id(), equalTo("2")); - assertThat(response.getHits().getAt(1).id(), equalTo("1")); - } - - @Test - public void testMultiValueCustomScriptBoost_withFunctionScore() throws ElasticsearchException, IOException { - - client().admin() - .indices() - .prepareCreate("test") - .setSettings(settingsBuilder().put("index.number_of_shards", 1).put("index.number_of_replicas", 0)) - .addMapping( - "type", - jsonBuilder().startObject().startObject("type").startObject("properties").startObject("snum") - .field("type", "string").endObject().startObject("dnum").field("type", "double").endObject() - .startObject("slnum").field("type", "long").endObject().startObject("gp").field("type", "geo_point") - .endObject().endObject().endObject().endObject()).execute().actionGet(); - client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().execute().actionGet(); - - String[] values = new String[100]; - String[] gp = new String[100]; - - long[] lValues = new long[100]; - double[] dValues = new double[100]; - int offset = 1; - for (int i = 0; i < values.length; i++) { - values[i] = "" + (i + offset); - gp[i] = "" + (i + offset) + "," + (i + offset); - lValues[i] = (i + offset); - dValues[i] = (i + offset); - } - client().index( - indexRequest("test") - .type("type1") - .id("1") - .source(jsonBuilder().startObject().field("test", "value check").field("snum", values).field("dnum", dValues) - .field("lnum", lValues).field("gp", gp).endObject())).actionGet(); - offset++; - for (int i = 0; i < values.length; i++) { - values[i] = "" + (i + offset); - gp[i] = "" + (i + offset) + "," + (i + offset); - lValues[i] = (i + offset); - dValues[i] = (i + offset); - } - client().index( - indexRequest("test") - .type("type1") - .id("2") - .source(jsonBuilder().startObject().field("test", "value check").field("snum", values).field("dnum", dValues) - .field("lnum", lValues).field("gp", gp).endObject())).actionGet(); - client().admin().indices().refresh(refreshRequest()).actionGet(); - - logger.info("running min(doc['num1'].value)"); - SearchResponse response = client() - .search(searchRequest() - .searchType(SearchType.QUERY_THEN_FETCH) - .source(searchSource() - .explain(true) - .query(functionScoreQuery( - termQuery("test", "value"), - scriptFunction("c_min = 1000; foreach (x : doc['snum'].values) { c_min = min(Integer.parseInt(x), c_min) } return c_min"))))) - .actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertThat(response.getHits().getAt(0).id(), equalTo("2")); - assertThat(response.getHits().getAt(1).id(), equalTo("1")); - - response = client() - .search(searchRequest() - .searchType(SearchType.QUERY_THEN_FETCH) - .source(searchSource() - .explain(true) - .query(functionScoreQuery( - termQuery("test", "value"), - scriptFunction("c_min = 1000; foreach (x : doc['lnum'].values) { c_min = min(x, c_min) } return c_min"))))) - .actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertThat(response.getHits().getAt(0).id(), equalTo("2")); - assertThat(response.getHits().getAt(1).id(), equalTo("1")); - - response = client() - .search(searchRequest() - .searchType(SearchType.QUERY_THEN_FETCH) - .source(searchSource() - .explain(true) - .query(functionScoreQuery( - termQuery("test", "value"), - scriptFunction("c_min = 1000; foreach (x : doc['dnum'].values) { c_min = min(x, c_min) } return c_min"))))) - .actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertThat(response.getHits().getAt(0).id(), equalTo("2")); - assertThat(response.getHits().getAt(1).id(), equalTo("1")); - - response = client() - .search(searchRequest() - .searchType(SearchType.QUERY_THEN_FETCH) - .source(searchSource() - .explain(true) - .query(functionScoreQuery( - termQuery("test", "value"), - scriptFunction("c_min = 1000; foreach (x : doc['gp'].values) { c_min = min(x.lat, c_min) } return c_min"))))) - .actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertThat(response.getHits().getAt(0).id(), equalTo("2")); - assertThat(response.getHits().getAt(1).id(), equalTo("1")); - } - - @Test - public void testCustomScriptBoost() throws Exception { - client().admin().indices().prepareCreate("test").setSettings(settingsBuilder().put("index.number_of_shards", 1)).execute() - .actionGet(); - - client().index( - indexRequest("test").type("type1").id("1") - .source(jsonBuilder().startObject().field("test", "value beck").field("num1", 1.0f).endObject())).actionGet(); - client().index( - indexRequest("test").type("type1").id("2") - .source(jsonBuilder().startObject().field("test", "value check").field("num1", 2.0f).endObject())).actionGet(); - client().admin().indices().refresh(refreshRequest()).actionGet(); - - logger.info("--- QUERY_THEN_FETCH"); - - logger.info("running doc['num1'].value"); - SearchResponse response = client().search( - searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( - searchSource().explain(true).query(customScoreQuery(termQuery("test", "value")).script("doc['num1'].value")))) - .actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertThat(response.getHits().getAt(0).id(), equalTo("2")); - assertThat(response.getHits().getAt(1).id(), equalTo("1")); - - logger.info("running -doc['num1'].value"); - response = client().search( - searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( - searchSource().explain(true).query(customScoreQuery(termQuery("test", "value")).script("-doc['num1'].value")))) - .actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertThat(response.getHits().getAt(0).id(), equalTo("1")); - assertThat(response.getHits().getAt(1).id(), equalTo("2")); - - logger.info("running pow(doc['num1'].value, 2)"); - response = client().search( - searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( - searchSource().explain(true) - .query(customScoreQuery(termQuery("test", "value")).script("pow(doc['num1'].value, 2)")))).actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertThat(response.getHits().getAt(0).id(), equalTo("2")); - assertThat(response.getHits().getAt(1).id(), equalTo("1")); - - logger.info("running max(doc['num1'].value, 1)"); - response = client().search( - searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( - searchSource().explain(true).query( - customScoreQuery(termQuery("test", "value")).script("max(doc['num1'].value, 1d)")))).actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertThat(response.getHits().getAt(0).id(), equalTo("2")); - assertThat(response.getHits().getAt(1).id(), equalTo("1")); - - logger.info("running doc['num1'].value * _score"); - response = client().search( - searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( - searchSource().explain(true).query( - customScoreQuery(termQuery("test", "value")).script("doc['num1'].value * _score")))).actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertThat(response.getHits().getAt(0).id(), equalTo("2")); - assertThat(response.getHits().getAt(1).id(), equalTo("1")); - - logger.info("running param1 * param2 * _score"); - response = client().search( - searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( - searchSource().explain(true).query( - customScoreQuery(termQuery("test", "value")).script("param1 * param2 * _score").param("param1", 2) - .param("param2", 2)))).actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertSearchHits(response, "1", "2"); - - logger.info("running param1 * param2 * _score with filter instead of query"); - response = client().search( - searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( - searchSource().explain(true).query( - customScoreQuery(termFilter("test", "value")).script("param1 * param2 * _score").param("param1", 2) - .param("param2", 2)))).actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertSearchHits(response, "1", "2"); - assertThat(response.getHits().getAt(0).score(), equalTo(4f)); // _score - // is - // always - // 1 - assertThat(response.getHits().getAt(1).score(), equalTo(4f)); // _score - // is - // always - // 1 - } - - @Test - public void testCustomScriptBoost_withFunctionScore() throws Exception { - client().admin().indices().prepareCreate("test").setSettings(settingsBuilder().put("index.number_of_shards", 1)).execute() - .actionGet(); - - client().index( - indexRequest("test").type("type1").id("1") - .source(jsonBuilder().startObject().field("test", "value beck").field("num1", 1.0f).endObject())).actionGet(); - client().index( - indexRequest("test").type("type1").id("2") - .source(jsonBuilder().startObject().field("test", "value check").field("num1", 2.0f).endObject())).actionGet(); - client().admin().indices().refresh(refreshRequest()).actionGet(); - - logger.info("--- QUERY_THEN_FETCH"); - - logger.info("running doc['num1'].value"); - SearchResponse response = client().search( - searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( - searchSource().explain(true).query( - functionScoreQuery(termQuery("test", "value"), scriptFunction("doc['num1'].value"))))).actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertThat(response.getHits().getAt(0).id(), equalTo("2")); - assertThat(response.getHits().getAt(1).id(), equalTo("1")); - - logger.info("running -doc['num1'].value"); - response = client().search( - searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( - searchSource().explain(true).query( - functionScoreQuery(termQuery("test", "value"), scriptFunction("-doc['num1'].value"))))).actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertThat(response.getHits().getAt(0).id(), equalTo("1")); - assertThat(response.getHits().getAt(1).id(), equalTo("2")); - - logger.info("running pow(doc['num1'].value, 2)"); - response = client().search( - searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( - searchSource().explain(true).query( - functionScoreQuery(termQuery("test", "value"), scriptFunction("pow(doc['num1'].value, 2)"))))).actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertThat(response.getHits().getAt(0).id(), equalTo("2")); - assertThat(response.getHits().getAt(1).id(), equalTo("1")); - - logger.info("running max(doc['num1'].value, 1)"); - response = client().search( - searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( - searchSource().explain(true).query( - functionScoreQuery(termQuery("test", "value"), scriptFunction("max(doc['num1'].value, 1d)"))))).actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertThat(response.getHits().getAt(0).id(), equalTo("2")); - assertThat(response.getHits().getAt(1).id(), equalTo("1")); - - logger.info("running doc['num1'].value * _score"); - response = client().search( - searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( - searchSource().explain(true).query( - functionScoreQuery(termQuery("test", "value"), scriptFunction("doc['num1'].value * _score"))))).actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertThat(response.getHits().getAt(0).id(), equalTo("2")); - assertThat(response.getHits().getAt(1).id(), equalTo("1")); - - logger.info("running param1 * param2 * _score"); - response = client().search( - searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( - searchSource().explain(true).query( - functionScoreQuery(termQuery("test", "value"), scriptFunction("param1 * param2 * _score") - .param("param1", 2).param("param2", 2))))).actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertSearchHits(response, "1", "2"); - - logger.info("running param1 * param2 * _score with filter instead of query"); - response = client().search( - searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( - searchSource().explain(true).query( - functionScoreQuery(termFilter("test", "value"), - scriptFunction("param1 * param2 * _score").param("param1", 2).param("param2", 2))))).actionGet(); - - assertThat(response.getHits().totalHits(), equalTo(2l)); - logger.info("Hit[0] {} Explanation {}", response.getHits().getAt(0).id(), response.getHits().getAt(0).explanation()); - logger.info("Hit[1] {} Explanation {}", response.getHits().getAt(1).id(), response.getHits().getAt(1).explanation()); - assertSearchHits(response, "1", "2"); - assertThat(response.getHits().getAt(0).score(), equalTo(4f)); // _score - // is - // always - // 1 - assertThat(response.getHits().getAt(1).score(), equalTo(4f)); // _score - // is - // always - // 1 - } - - @Test - public void testTriggerBooleanScorer() throws Exception { - client().admin().indices().prepareCreate("test").setSettings(settingsBuilder().put("index.number_of_shards", 1)).execute() - .actionGet(); - - client().prepareIndex("test", "type", "1").setSource("field", "value1", "color", "red").execute().actionGet(); - client().prepareIndex("test", "type", "2").setSource("field", "value2", "color", "blue").execute().actionGet(); - client().prepareIndex("test", "type", "3").setSource("field", "value3", "color", "red").execute().actionGet(); - client().prepareIndex("test", "type", "4").setSource("field", "value4", "color", "blue").execute().actionGet(); - client().admin().indices().prepareRefresh().execute().actionGet(); - SearchResponse searchResponse = client().prepareSearch("test") - .setQuery(customFiltersScoreQuery(fuzzyQuery("field", "value")).add(FilterBuilders.idsFilter("type").addIds("1"), 3)) - .execute().actionGet(); - assertNoFailures(searchResponse); - - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - } - - @Test - public void testTriggerBooleanScorer_withFunctionScore() throws Exception { - client().admin().indices().prepareCreate("test").setSettings(settingsBuilder().put("index.number_of_shards", 1)).execute() - .actionGet(); - - client().prepareIndex("test", "type", "1").setSource("field", "value1", "color", "red").execute().actionGet(); - client().prepareIndex("test", "type", "2").setSource("field", "value2", "color", "blue").execute().actionGet(); - client().prepareIndex("test", "type", "3").setSource("field", "value3", "color", "red").execute().actionGet(); - client().prepareIndex("test", "type", "4").setSource("field", "value4", "color", "blue").execute().actionGet(); - client().admin().indices().prepareRefresh().execute().actionGet(); - SearchResponse searchResponse = client() - .prepareSearch("test") - .setQuery( - functionScoreQuery(fuzzyQuery("field", "value")).add(FilterBuilders.idsFilter("type").addIds("1"), - factorFunction(3))).execute().actionGet(); - assertThat(Arrays.toString(searchResponse.getShardFailures()), searchResponse.getFailedShards(), equalTo(0)); - - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - } - - @Test - public void testCustomFiltersScore() throws Exception { - client().admin().indices().prepareCreate("test").setSettings(settingsBuilder().put("index.number_of_shards", 1)).execute() - .actionGet(); - - client().prepareIndex("test", "type", "1").setSource("field", "value1", "color", "red").execute().actionGet(); - client().prepareIndex("test", "type", "2").setSource("field", "value2", "color", "blue").execute().actionGet(); - client().prepareIndex("test", "type", "3").setSource("field", "value3", "color", "red").execute().actionGet(); - client().prepareIndex("test", "type", "4").setSource("field", "value4", "color", "blue").execute().actionGet(); - - client().admin().indices().prepareRefresh().execute().actionGet(); - - SearchResponse searchResponse = client() - .prepareSearch("test") - .setQuery( - customFiltersScoreQuery(matchAllQuery()).add(termFilter("field", "value4"), "2").add(termFilter("field", "value2"), - "3")).setExplain(true).execute().actionGet(); - - assertNoFailures(searchResponse); - - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), equalTo("2")); - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(3.0f)); - logger.info("--> Hit[0] {} Explanation {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0).explanation()); - assertThat(searchResponse.getHits().getAt(1).id(), equalTo("4")); - assertThat(searchResponse.getHits().getAt(1).score(), equalTo(2.0f)); - assertThat(searchResponse.getHits().getAt(2).id(), anyOf(equalTo("1"), equalTo("3"))); - assertThat(searchResponse.getHits().getAt(2).score(), equalTo(1.0f)); - assertThat(searchResponse.getHits().getAt(3).id(), anyOf(equalTo("1"), equalTo("3"))); - assertThat(searchResponse.getHits().getAt(3).score(), equalTo(1.0f)); - - searchResponse = client() - .prepareSearch("test") - .setQuery( - customFiltersScoreQuery(matchAllQuery()).add(termFilter("field", "value4"), 2) - .add(termFilter("field", "value2"), 3)).setExplain(true).execute().actionGet(); - - assertNoFailures(searchResponse); - - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), equalTo("2")); - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(3.0f)); - logger.info("--> Hit[0] {} Explanation {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0).explanation()); - assertThat(searchResponse.getHits().getAt(1).id(), equalTo("4")); - assertThat(searchResponse.getHits().getAt(1).score(), equalTo(2.0f)); - assertThat(searchResponse.getHits().getAt(2).id(), anyOf(equalTo("1"), equalTo("3"))); - assertThat(searchResponse.getHits().getAt(2).score(), equalTo(1.0f)); - assertThat(searchResponse.getHits().getAt(3).id(), anyOf(equalTo("1"), equalTo("3"))); - assertThat(searchResponse.getHits().getAt(3).score(), equalTo(1.0f)); - - searchResponse = client() - .prepareSearch("test") - .setQuery( - customFiltersScoreQuery(matchAllQuery()).scoreMode("total").add(termFilter("field", "value4"), 2) - .add(termFilter("field", "value1"), 3).add(termFilter("color", "red"), 5)).setExplain(true).execute() - .actionGet(); - - assertNoFailures(searchResponse); - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), equalTo("1")); - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(8.0f)); - logger.info("--> Hit[0] {} Explanation {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0).explanation()); - - searchResponse = client() - .prepareSearch("test") - .setQuery( - customFiltersScoreQuery(matchAllQuery()).scoreMode("max").add(termFilter("field", "value4"), 2) - .add(termFilter("field", "value1"), 3).add(termFilter("color", "red"), 5)).setExplain(true).execute() - .actionGet(); - - assertNoFailures(searchResponse); - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), anyOf(equalTo("1"), equalTo("3"))); // could - // be - // both - // depending - // on - // the - // order - // of - // the - // docs - // internally - // (lucene - // order) - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(5.0f)); - logger.info("--> Hit[0] {} Explanation {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0).explanation()); - - searchResponse = client() - .prepareSearch("test") - .setQuery( - customFiltersScoreQuery(matchAllQuery()).scoreMode("avg").add(termFilter("field", "value4"), 2) - .add(termFilter("field", "value1"), 3).add(termFilter("color", "red"), 5)).setExplain(true).execute() - .actionGet(); - - assertNoFailures(searchResponse); - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), equalTo("3")); - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(5.0f)); - logger.info("--> Hit[0] {} Explanation {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0).explanation()); - assertThat(searchResponse.getHits().getAt(1).id(), equalTo("1")); - assertThat(searchResponse.getHits().getAt(1).score(), equalTo(4.0f)); - logger.info("--> Hit[1] {} Explanation {}", searchResponse.getHits().getAt(1).id(), searchResponse.getHits().getAt(1).explanation()); - - searchResponse = client() - .prepareSearch("test") - .setQuery( - customFiltersScoreQuery(matchAllQuery()).scoreMode("min").add(termFilter("field", "value4"), 2) - .add(termFilter("field", "value1"), 3).add(termFilter("color", "red"), 5)).setExplain(true).execute() - .actionGet(); - - assertNoFailures(searchResponse); - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), equalTo("3")); - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(5.0f)); - logger.info("--> Hit[0] {} Explanation {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0).explanation()); - assertThat(searchResponse.getHits().getAt(1).id(), equalTo("1")); - assertThat(searchResponse.getHits().getAt(1).score(), equalTo(3.0f)); - assertThat(searchResponse.getHits().getAt(2).id(), equalTo("4")); - assertThat(searchResponse.getHits().getAt(2).score(), equalTo(2.0f)); - assertThat(searchResponse.getHits().getAt(3).id(), equalTo("2")); - assertThat(searchResponse.getHits().getAt(3).score(), equalTo(1.0f)); - - searchResponse = client() - .prepareSearch("test") - .setQuery( - customFiltersScoreQuery(matchAllQuery()).scoreMode("multiply").add(termFilter("field", "value4"), 2) - .add(termFilter("field", "value1"), 3).add(termFilter("color", "red"), 5)).setExplain(true).execute() - .actionGet(); - - assertNoFailures(searchResponse); - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), equalTo("1")); - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(15.0f)); - logger.info("--> Hit[0] {} Explanation {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0).explanation()); - assertThat(searchResponse.getHits().getAt(1).id(), equalTo("3")); - assertThat(searchResponse.getHits().getAt(1).score(), equalTo(5.0f)); - assertThat(searchResponse.getHits().getAt(2).id(), equalTo("4")); - assertThat(searchResponse.getHits().getAt(2).score(), equalTo(2.0f)); - assertThat(searchResponse.getHits().getAt(3).id(), equalTo("2")); - assertThat(searchResponse.getHits().getAt(3).score(), equalTo(1.0f)); - - searchResponse = client() - .prepareSearch("test") - .setQuery( - customFiltersScoreQuery(termsQuery("field", "value1", "value2", "value3", "value4")).scoreMode("first") - .add(termFilter("field", "value4"), 2).add(termFilter("field", "value3"), 3) - .add(termFilter("field", "value2"), 4)).setExplain(true).execute().actionGet(); - - assertNoFailures(searchResponse); - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), equalTo("2")); - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(searchResponse.getHits().getAt(0).explanation().getValue())); - logger.info("--> Hit[0] {} Explanation {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0).explanation()); - assertThat(searchResponse.getHits().getAt(1).id(), equalTo("3")); - assertThat(searchResponse.getHits().getAt(1).score(), equalTo(searchResponse.getHits().getAt(1).explanation().getValue())); - assertThat(searchResponse.getHits().getAt(2).id(), equalTo("4")); - assertThat(searchResponse.getHits().getAt(2).score(), equalTo(searchResponse.getHits().getAt(2).explanation().getValue())); - assertThat(searchResponse.getHits().getAt(3).id(), equalTo("1")); - assertThat(searchResponse.getHits().getAt(3).score(), equalTo(searchResponse.getHits().getAt(3).explanation().getValue())); - - searchResponse = client() - .prepareSearch("test") - .setQuery( - customFiltersScoreQuery(termsQuery("field", "value1", "value2", "value3", "value4")).scoreMode("multiply") - .add(termFilter("field", "value4"), 2).add(termFilter("field", "value1"), 3) - .add(termFilter("color", "red"), 5)).setExplain(true).execute().actionGet(); - - assertNoFailures(searchResponse); - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), equalTo("1")); - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(searchResponse.getHits().getAt(0).explanation().getValue())); - logger.info("--> Hit[0] {} Explanation {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0).explanation()); - assertThat(searchResponse.getHits().getAt(1).id(), equalTo("3")); - assertThat(searchResponse.getHits().getAt(1).score(), equalTo(searchResponse.getHits().getAt(1).explanation().getValue())); - assertThat(searchResponse.getHits().getAt(2).id(), equalTo("4")); - assertThat(searchResponse.getHits().getAt(2).score(), equalTo(searchResponse.getHits().getAt(2).explanation().getValue())); - assertThat(searchResponse.getHits().getAt(3).id(), equalTo("2")); - assertThat(searchResponse.getHits().getAt(3).score(), equalTo(searchResponse.getHits().getAt(3).explanation().getValue())); - } - - @Test - public void testCustomFiltersScore_withFunctionScore() throws Exception { - client().admin().indices().prepareCreate("test").setSettings(settingsBuilder().put("index.number_of_shards", 1)).execute() - .actionGet(); - - client().prepareIndex("test", "type", "1").setSource("field", "value1", "color", "red").execute().actionGet(); - client().prepareIndex("test", "type", "2").setSource("field", "value2", "color", "blue").execute().actionGet(); - client().prepareIndex("test", "type", "3").setSource("field", "value3", "color", "red").execute().actionGet(); - client().prepareIndex("test", "type", "4").setSource("field", "value4", "color", "blue").execute().actionGet(); - - client().admin().indices().prepareRefresh().execute().actionGet(); - - SearchResponse searchResponse = client() - .prepareSearch("test") - .setQuery( - functionScoreQuery(matchAllQuery()) - .add(termFilter("field", "value4"), scriptFunction("2")).add( - termFilter("field", "value2"), scriptFunction("3"))).setExplain(true) - .execute().actionGet(); - - assertThat(Arrays.toString(searchResponse.getShardFailures()), searchResponse.getFailedShards(), equalTo(0)); - - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), equalTo("2")); - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(3.0f)); - logger.info("--> Hit[0] {} Explanation {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0).explanation()); - assertThat(searchResponse.getHits().getAt(1).id(), equalTo("4")); - assertThat(searchResponse.getHits().getAt(1).score(), equalTo(2.0f)); - assertThat(searchResponse.getHits().getAt(2).id(), anyOf(equalTo("1"), equalTo("3"))); - assertThat(searchResponse.getHits().getAt(2).score(), equalTo(1.0f)); - assertThat(searchResponse.getHits().getAt(3).id(), anyOf(equalTo("1"), equalTo("3"))); - assertThat(searchResponse.getHits().getAt(3).score(), equalTo(1.0f)); - - searchResponse = client() - .prepareSearch("test") - .setQuery( - functionScoreQuery(matchAllQuery()).add(termFilter("field", "value4"), factorFunction(2)).add( - termFilter("field", "value2"), factorFunction(3))).setExplain(true).execute().actionGet(); - - assertThat(Arrays.toString(searchResponse.getShardFailures()), searchResponse.getFailedShards(), equalTo(0)); - - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), equalTo("2")); - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(3.0f)); - logger.info("--> Hit[0] {} Explanation {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0).explanation()); - assertThat(searchResponse.getHits().getAt(1).id(), equalTo("4")); - assertThat(searchResponse.getHits().getAt(1).score(), equalTo(2.0f)); - assertThat(searchResponse.getHits().getAt(2).id(), anyOf(equalTo("1"), equalTo("3"))); - assertThat(searchResponse.getHits().getAt(2).score(), equalTo(1.0f)); - assertThat(searchResponse.getHits().getAt(3).id(), anyOf(equalTo("1"), equalTo("3"))); - assertThat(searchResponse.getHits().getAt(3).score(), equalTo(1.0f)); - - searchResponse = client() - .prepareSearch("test") - .setQuery( - functionScoreQuery(matchAllQuery()).scoreMode("sum") - .add(termFilter("field", "value4"), factorFunction(2)) - .add(termFilter("field", "value1"), factorFunction(3)) - .add(termFilter("color", "red"), factorFunction(5))).setExplain(true).execute() - .actionGet(); - - assertThat(Arrays.toString(searchResponse.getShardFailures()), searchResponse.getFailedShards(), equalTo(0)); - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), equalTo("1")); - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(8.0f)); - logger.info("--> Hit[0] {} Explanation {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0).explanation()); - - searchResponse = client() - .prepareSearch("test") - .setQuery( - functionScoreQuery(matchAllQuery()).scoreMode("max") - .add(termFilter("field", "value4"), factorFunction(2)) - .add(termFilter("field", "value1"), factorFunction(3)) - .add(termFilter("color", "red"), factorFunction(5))).setExplain(true).execute() - .actionGet(); - - assertThat(Arrays.toString(searchResponse.getShardFailures()), searchResponse.getFailedShards(), equalTo(0)); - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), anyOf(equalTo("1"), equalTo("3"))); // could - // be - // both - // depending - // on - // the - // order - // of - // the - // docs - // internally - // (lucene - // order) - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(5.0f)); - logger.info("--> Hit[0] {} Explanation {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0).explanation()); - - searchResponse = client() - .prepareSearch("test") - .setQuery( - functionScoreQuery(matchAllQuery()).scoreMode("avg") - .add(termFilter("field", "value4"), factorFunction(2)) - .add(termFilter("field", "value1"), factorFunction(3)) - .add(termFilter("color", "red"), factorFunction(5))).setExplain(true).execute() - .actionGet(); - - assertThat(Arrays.toString(searchResponse.getShardFailures()), searchResponse.getFailedShards(), equalTo(0)); - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), equalTo("3")); - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(5.0f)); - logger.info("--> Hit[0] {} Explanation {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0).explanation()); - assertThat(searchResponse.getHits().getAt(1).id(), equalTo("1")); - assertThat(searchResponse.getHits().getAt(1).score(), equalTo(4.0f)); - logger.info("--> Hit[1] {} Explanation {}", searchResponse.getHits().getAt(1).id(), searchResponse.getHits().getAt(1).explanation()); - - searchResponse = client() - .prepareSearch("test") - .setQuery( - functionScoreQuery(matchAllQuery()).scoreMode("min") - .add(termFilter("field", "value4"), factorFunction(2)) - .add(termFilter("field", "value1"), factorFunction(3)) - .add(termFilter("color", "red"), factorFunction(5))).setExplain(true).execute() - .actionGet(); - - assertThat(Arrays.toString(searchResponse.getShardFailures()), searchResponse.getFailedShards(), equalTo(0)); - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), equalTo("3")); - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(5.0f)); - logger.info("--> Hit[0] {} Explanation {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0).explanation()); - assertThat(searchResponse.getHits().getAt(1).id(), equalTo("1")); - assertThat(searchResponse.getHits().getAt(1).score(), equalTo(3.0f)); - assertThat(searchResponse.getHits().getAt(2).id(), equalTo("4")); - assertThat(searchResponse.getHits().getAt(2).score(), equalTo(2.0f)); - assertThat(searchResponse.getHits().getAt(3).id(), equalTo("2")); - assertThat(searchResponse.getHits().getAt(3).score(), equalTo(1.0f)); - - searchResponse = client() - .prepareSearch("test") - .setQuery( - functionScoreQuery(matchAllQuery()).scoreMode("multiply") - .add(termFilter("field", "value4"), factorFunction(2)) - .add(termFilter("field", "value1"), factorFunction(3)) - .add(termFilter("color", "red"), factorFunction(5))).setExplain(true).execute() - .actionGet(); - - assertThat(Arrays.toString(searchResponse.getShardFailures()), searchResponse.getFailedShards(), equalTo(0)); - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), equalTo("1")); - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(15.0f)); - logger.info("--> Hit[0] {} Explanation {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0).explanation()); - assertThat(searchResponse.getHits().getAt(1).id(), equalTo("3")); - assertThat(searchResponse.getHits().getAt(1).score(), equalTo(5.0f)); - assertThat(searchResponse.getHits().getAt(2).id(), equalTo("4")); - assertThat(searchResponse.getHits().getAt(2).score(), equalTo(2.0f)); - assertThat(searchResponse.getHits().getAt(3).id(), equalTo("2")); - assertThat(searchResponse.getHits().getAt(3).score(), equalTo(1.0f)); - - searchResponse = client() - .prepareSearch("test") - .setQuery( - functionScoreQuery(termsQuery("field", "value1", "value2", "value3", "value4")).scoreMode("first") - .add(termFilter("field", "value4"), factorFunction(2)) - .add(termFilter("field", "value3"), factorFunction(3)) - .add(termFilter("field", "value2"), factorFunction(4))).setExplain(true).execute() - .actionGet(); - - assertThat(Arrays.toString(searchResponse.getShardFailures()), searchResponse.getFailedShards(), equalTo(0)); - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), equalTo("2")); - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(searchResponse.getHits().getAt(0).explanation().getValue())); - logger.info("--> Hit[0] {} Explanation {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0).explanation()); - assertThat(searchResponse.getHits().getAt(1).id(), equalTo("3")); - assertThat(searchResponse.getHits().getAt(1).score(), equalTo(searchResponse.getHits().getAt(1).explanation().getValue())); - assertThat(searchResponse.getHits().getAt(2).id(), equalTo("4")); - assertThat(searchResponse.getHits().getAt(2).score(), equalTo(searchResponse.getHits().getAt(2).explanation().getValue())); - assertThat(searchResponse.getHits().getAt(3).id(), equalTo("1")); - assertThat(searchResponse.getHits().getAt(3).score(), equalTo(searchResponse.getHits().getAt(3).explanation().getValue())); - - searchResponse = client() - .prepareSearch("test") - .setQuery( - functionScoreQuery(termsQuery("field", "value1", "value2", "value3", "value4")).scoreMode("multiply") - .add(termFilter("field", "value4"), factorFunction(2)) - .add(termFilter("field", "value1"), factorFunction(3)) - .add(termFilter("color", "red"), factorFunction(5))).setExplain(true).execute() - .actionGet(); - - assertThat(Arrays.toString(searchResponse.getShardFailures()), searchResponse.getFailedShards(), equalTo(0)); - assertThat(searchResponse.getHits().totalHits(), equalTo(4l)); - assertThat(searchResponse.getHits().getAt(0).id(), equalTo("1")); - assertThat(searchResponse.getHits().getAt(0).score(), equalTo(searchResponse.getHits().getAt(0).explanation().getValue())); - logger.info("--> Hit[0] {} Explanation {}", searchResponse.getHits().getAt(0).id(), searchResponse.getHits().getAt(0).explanation()); - assertThat(searchResponse.getHits().getAt(1).id(), equalTo("3")); - assertThat(searchResponse.getHits().getAt(1).score(), equalTo(searchResponse.getHits().getAt(1).explanation().getValue())); - assertThat(searchResponse.getHits().getAt(2).id(), equalTo("4")); - assertThat(searchResponse.getHits().getAt(2).score(), equalTo(searchResponse.getHits().getAt(2).explanation().getValue())); - assertThat(searchResponse.getHits().getAt(3).id(), equalTo("2")); - assertThat(searchResponse.getHits().getAt(3).score(), equalTo(searchResponse.getHits().getAt(3).explanation().getValue())); - } -} diff --git a/src/test/java/org/elasticsearch/search/sort/SimpleSortTests.java b/src/test/java/org/elasticsearch/search/sort/SimpleSortTests.java index 265179d7c4b..15cf6652462 100644 --- a/src/test/java/org/elasticsearch/search/sort/SimpleSortTests.java +++ b/src/test/java/org/elasticsearch/search/sort/SimpleSortTests.java @@ -35,6 +35,8 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.index.mapper.Uid; import org.elasticsearch.index.query.FilterBuilders; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHitField; import org.elasticsearch.test.ElasticsearchIntegrationTest; @@ -245,21 +247,21 @@ public class SimpleSortTests extends ElasticsearchIntegrationTest { refresh(); - SearchResponse searchResponse = client().prepareSearch("test").setQuery(customScoreQuery(matchAllQuery()).script("_source.field")).execute().actionGet(); + SearchResponse searchResponse = client().prepareSearch("test").setQuery(QueryBuilders.functionScoreQuery(matchAllQuery(), ScoreFunctionBuilders.scriptFunction("_source.field"))).execute().actionGet(); assertThat(searchResponse.getHits().getAt(0).getId(), equalTo("1")); assertThat(searchResponse.getHits().getAt(1).score(), Matchers.lessThan(searchResponse.getHits().getAt(0).score())); assertThat(searchResponse.getHits().getAt(1).getId(), equalTo("2")); assertThat(searchResponse.getHits().getAt(2).score(), Matchers.lessThan(searchResponse.getHits().getAt(1).score())); assertThat(searchResponse.getHits().getAt(2).getId(), equalTo("3")); - searchResponse = client().prepareSearch("test").setQuery(customScoreQuery(matchAllQuery()).script("_source.field")).addSort("_score", SortOrder.DESC).execute().actionGet(); + searchResponse = client().prepareSearch("test").setQuery(QueryBuilders.functionScoreQuery(matchAllQuery(), ScoreFunctionBuilders.scriptFunction("_source.field"))).addSort("_score", SortOrder.DESC).execute().actionGet(); assertThat(searchResponse.getHits().getAt(0).getId(), equalTo("1")); assertThat(searchResponse.getHits().getAt(1).score(), Matchers.lessThan(searchResponse.getHits().getAt(0).score())); assertThat(searchResponse.getHits().getAt(1).getId(), equalTo("2")); assertThat(searchResponse.getHits().getAt(2).score(), Matchers.lessThan(searchResponse.getHits().getAt(1).score())); assertThat(searchResponse.getHits().getAt(2).getId(), equalTo("3")); - searchResponse = client().prepareSearch("test").setQuery(customScoreQuery(matchAllQuery()).script("_source.field")).addSort("_score", SortOrder.DESC).execute().actionGet(); + searchResponse = client().prepareSearch("test").setQuery(QueryBuilders.functionScoreQuery(matchAllQuery(), ScoreFunctionBuilders.scriptFunction("_source.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"));