Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Rest Api Compatibility] Typed query #75453

Merged
merged 23 commits into from
Aug 3, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions rest-api-spec/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,8 @@ tasks.named("yamlRestCompatTest").configure {
'cluster.voting_config_exclusions/10_basic/Throw exception when adding voting config exclusion and specifying both node_ids and node_names',
'cluster.voting_config_exclusions/10_basic/Throw exception when adding voting config exclusion without specifying nodes',
'indices.flush/10_basic/Index synced flush rest test',
'search.aggregation/200_top_hits_metric/top_hits aggregation with sequence numbers',
'search.aggregation/200_top_hits_metric/top_hits aggregation with sequence numbers',//#42809 nested path and nested filter
'search/310_match_bool_prefix/multi_match multiple fields with cutoff_frequency throws exception', //cutoff_frequency
'search/340_type_query/type query', // type_query - probably should behave like match_all
] + v7compatibilityNotSupportedTests())
.join(',')

Expand Down Expand Up @@ -222,6 +221,8 @@ tasks.named("transformV7RestTests").configure({ task ->
task.removeWarningForTest("the default value for the ?wait_for_active_shards parameter will change from '0' to 'index-setting' in version 8; " +
"specify '?wait_for_active_shards=index-setting' to adopt the future default behaviour, or '?wait_for_active_shards=0' to preserve today's behaviour"
, "?wait_for_active_shards default is deprecated")

task.replaceValueInMatch("hits.total", 1, "type query") // 340_type_query.yml
})

tasks.register('enforceYamlTestConvention').configure {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than adding this back into the core server package, could we put it into a separate module instead? I think that would avoid changes to Node as well.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good idea, will do this

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the sake of simplicity I kept this query in the server module (same package as previously)
I was worried that if we keep all v7 queries in single module it will have far too many dependencies.

* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

package org.elasticsearch.index.query;

import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.ParseField;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.index.mapper.MapperService;

import java.io.IOException;

public class TypeQueryV7Builder extends AbstractQueryBuilder<TypeQueryV7Builder> {
public static final String NAME = "type";
public static final ParseField NAME_V7 = new ParseField("type").forRestApiVersion(RestApiVersion.equalTo(RestApiVersion.V_7));
private static final ParseField VALUE_FIELD = new ParseField("value");
private static final ObjectParser<TypeQueryV7Builder, Void> PARSER = new ObjectParser<>(NAME, TypeQueryV7Builder::new);

static {
PARSER.declareString(QueryBuilder::queryName,
AbstractQueryBuilder.NAME_FIELD.forRestApiVersion(RestApiVersion.equalTo(RestApiVersion.V_7)));
PARSER.declareFloat(QueryBuilder::boost,
AbstractQueryBuilder.BOOST_FIELD.forRestApiVersion(RestApiVersion.equalTo(RestApiVersion.V_7)));
PARSER.declareString((queryBuilder, value) -> {},
VALUE_FIELD.forRestApiVersion(RestApiVersion.equalTo(RestApiVersion.V_7)));
}

public TypeQueryV7Builder() {
}

/**
* Read from a stream.
*/
public TypeQueryV7Builder(StreamInput in) throws IOException {
super(in);
}

@Override
protected void doWriteTo(StreamOutput out) throws IOException {
}

@Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME);
builder.field(VALUE_FIELD.getPreferredName(), MapperService.SINGLE_MAPPING_NAME);
printBoostAndQueryName(builder);
builder.endObject();
}

@Override
protected Query doToQuery(SearchExecutionContext context) throws IOException {
return new MatchAllDocsQuery();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We do actually still have type information available: context.mappingLookup().getMapping().getRoot().name(). So you could check against the top-level type and then return a MatchAll/MatchNone depending on whether or not you get a match.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so you suggest to check if the value used on a type query is _doc (this is the only type we can have, right?) then return matchAll otherwise matchNone?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what values can I expect from context.mappingLookup().getMapping().getRoot().name() ?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can still specify non-_doc type names in 7x indexes. context .... name() will return the type name of the current index.

}

@Override
protected boolean doEquals(TypeQueryV7Builder other) {
return true;
}

@Override
protected int doHashCode() {
return 0;
}

public static TypeQueryV7Builder fromXContent(XContentParser parser) throws IOException {
try {
return PARSER.apply(parser, null);
} catch (IllegalArgumentException e) {
throw new ParsingException(parser.getTokenLocation(), e.getMessage(), e);
}
}

@Override
public String getWriteableName() {
return NAME;
}
}
10 changes: 6 additions & 4 deletions server/src/main/java/org/elasticsearch/node/Node.java
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ protected Node(final Environment initialEnvironment,
.flatMap(p -> p.getNamedXContent().stream()),
ClusterModule.getNamedXWriteables().stream())
.flatMap(Function.identity()).collect(toList()),
getCompatibleNamedXContents()
getCompatibleNamedXContents(searchModule)
);
final Map<String, SystemIndices.Feature> featuresMap = pluginsService
.filterPlugins(SystemIndexPlugin.class)
Expand Down Expand Up @@ -738,9 +738,11 @@ protected Node(final Environment initialEnvironment,
}

// package scope for testing
List<NamedXContentRegistry.Entry> getCompatibleNamedXContents() {
return pluginsService.filterPlugins(Plugin.class).stream()
.flatMap(p -> p.getNamedXContentForCompatibility().stream()).collect(toList());
List<NamedXContentRegistry.Entry> getCompatibleNamedXContents(SearchModule searchModule) {
return Stream.of(pluginsService.filterPlugins(Plugin.class).stream()
.flatMap(p -> p.getNamedXContentForCompatibility().stream()),
searchModule.getNamedXContentForCompatibility().stream())
.flatMap(Function.identity()).collect(toList());
}

protected TransportService newTransportService(Settings settings, Transport transport, ThreadPool threadPool,
Expand Down
11 changes: 11 additions & 0 deletions server/src/main/java/org/elasticsearch/search/SearchModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.BoostingQueryBuilder;
import org.elasticsearch.index.query.CombinedFieldsQueryBuilder;
Expand Down Expand Up @@ -67,6 +68,7 @@
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.index.query.TermsSetQueryBuilder;
import org.elasticsearch.index.query.TypeQueryV7Builder;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.elasticsearch.index.query.WrapperQueryBuilder;
import org.elasticsearch.index.query.functionscore.ExponentialDecayFunctionBuilder;
Expand Down Expand Up @@ -255,6 +257,7 @@
import java.util.function.Consumer;
import java.util.function.Function;

import static java.util.Collections.emptyList;
import static java.util.Collections.unmodifiableMap;
import static java.util.Objects.requireNonNull;

Expand Down Expand Up @@ -893,4 +896,12 @@ private void registerBoolQuery(ParseField name, Writeable.Reader reader) {
public FetchPhase getFetchPhase() {
return new FetchPhase(fetchSubPhases);
}

public List<NamedXContentRegistry.Entry> getNamedXContentForCompatibility() {
if (RestApiVersion.minimumSupported() == RestApiVersion.V_7) {
return List.of(
new NamedXContentRegistry.Entry(QueryBuilder.class, TypeQueryV7Builder.NAME_V7, TypeQueryV7Builder::fromXContent));
}
return emptyList();
}
}
16 changes: 9 additions & 7 deletions server/src/test/java/org/elasticsearch/node/NodeTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import org.elasticsearch.indices.breaker.CircuitBreakerService;
import org.elasticsearch.plugins.CircuitBreakerPlugin;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.search.SearchModule;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.InternalTestCluster;
import org.elasticsearch.test.MockHttpTransport;
Expand All @@ -55,6 +56,7 @@
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.Mockito.mock;

@LuceneTestCase.SuppressFileSystems(value = "ExtrasFS")
public class NodeTests extends ESTestCase {
Expand Down Expand Up @@ -340,25 +342,25 @@ interface MockRestApiVersion {
RestApiVersion minimumRestCompatibilityVersion();
}

static MockRestApiVersion MockCompatibleVersion = Mockito.mock(MockRestApiVersion.class);
static MockRestApiVersion MockCompatibleVersion = mock(MockRestApiVersion.class);

static NamedXContentRegistry.Entry v7CompatibleEntries = new NamedXContentRegistry.Entry(Integer.class,
new ParseField("name"), Mockito.mock(ContextParser.class));
new ParseField("name"), mock(ContextParser.class));
static NamedXContentRegistry.Entry v8CompatibleEntries = new NamedXContentRegistry.Entry(Integer.class,
new ParseField("name2"), Mockito.mock(ContextParser.class));
new ParseField("name2"), mock(ContextParser.class));

public static class TestRestCompatibility1 extends Plugin {

@Override
public List<NamedXContentRegistry.Entry> getNamedXContentForCompatibility() {
// real plugin will use CompatibleVersion.minimumRestCompatibilityVersion()
if (/*CompatibleVersion.minimumRestCompatibilityVersion()*/
if (/*RestApiVersion.minimumSupported() == */
MockCompatibleVersion.minimumRestCompatibilityVersion().equals(RestApiVersion.V_7)) {
//return set of N-1 entries
return List.of(v7CompatibleEntries);
}
// after major release, new compatible apis can be added before the old ones are removed.
if (/*CompatibleVersion.minimumRestCompatibilityVersion()*/
if (/*RestApiVersion.minimumSupported() == */
MockCompatibleVersion.minimumRestCompatibilityVersion().equals(RestApiVersion.V_8)) {
return List.of(v8CompatibleEntries);

Expand All @@ -381,7 +383,7 @@ public void testLoadingMultipleRestCompatibilityPlugins() throws IOException {
plugins.add(TestRestCompatibility1.class);

try (Node node = new MockNode(settings.build(), plugins)) {
List<NamedXContentRegistry.Entry> compatibleNamedXContents = node.getCompatibleNamedXContents();
List<NamedXContentRegistry.Entry> compatibleNamedXContents = node.getCompatibleNamedXContents(mock(SearchModule.class));
assertThat(compatibleNamedXContents, contains(v7CompatibleEntries));
}
}
Expand All @@ -396,7 +398,7 @@ public void testLoadingMultipleRestCompatibilityPlugins() throws IOException {
plugins.add(TestRestCompatibility1.class);

try (Node node = new MockNode(settings.build(), plugins)) {
List<NamedXContentRegistry.Entry> compatibleNamedXContents = node.getCompatibleNamedXContents();
List<NamedXContentRegistry.Entry> compatibleNamedXContents = node.getCompatibleNamedXContents(mock(SearchModule.class));
assertThat(compatibleNamedXContents, contains(v8CompatibleEntries));
}
}
Expand Down