Merge branch 'master' into feature/ingest

This commit is contained in:
javanna 2015-11-24 10:23:53 +01:00 committed by Luca Cavanna
commit eeb51ce8d0
296 changed files with 3532 additions and 13426 deletions

View File

@ -465,9 +465,10 @@ gradle run --debug-jvm
== Building with extra plugins == Building with extra plugins
Additional plugins may be built alongside elasticsearch, where their Additional plugins may be built alongside elasticsearch, where their
dependency on elasticsearch will be substituted with the local elasticsearch dependency on elasticsearch will be substituted with the local elasticsearch
build. To add your plugin, check it out into the extra-plugins directory. build. To add your plugin, create a directory called x-plugins as a sibling
The build will automatically pick it up. You can verify the plugin is of elasticsearch. Checkout your plugin underneath x-plugins and the build
included as part of the build by checking the projects of the build. will automatically pick it up. You can verify the plugin is included as part
of the build by checking the projects of the build.
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
gradle projects gradle projects

View File

@ -17,10 +17,19 @@
* under the License. * under the License.
*/ */
plugins { // we must use buildscript + apply so that an external plugin
id 'groovy' // can apply this file, since the plugins directive is not
id 'com.bmuschko.nexus' version '2.3.1' // supported through file includes
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.bmuschko:gradle-nexus-plugin:2.3.1'
}
} }
apply plugin: 'groovy'
apply plugin: 'com.bmuschko.nexus'
// TODO: move common IDE configuration to a common file to include // TODO: move common IDE configuration to a common file to include
apply plugin: 'idea' apply plugin: 'idea'
apply plugin: 'eclipse' apply plugin: 'eclipse'

View File

@ -2,6 +2,7 @@ package com.carrotsearch.gradle.junit4
import com.carrotsearch.ant.tasks.junit4.ListenersList import com.carrotsearch.ant.tasks.junit4.ListenersList
import com.carrotsearch.ant.tasks.junit4.listeners.AggregatedEventListener import com.carrotsearch.ant.tasks.junit4.listeners.AggregatedEventListener
import com.esotericsoftware.kryo.serializers.FieldSerializer
import groovy.xml.NamespaceBuilder import groovy.xml.NamespaceBuilder
import groovy.xml.NamespaceBuilderSupport import groovy.xml.NamespaceBuilderSupport
import org.apache.tools.ant.BuildException import org.apache.tools.ant.BuildException
@ -58,6 +59,14 @@ class RandomizedTestingTask extends DefaultTask {
@Input @Input
boolean enableSystemAssertions = true boolean enableSystemAssertions = true
@Optional
@Input
boolean leaveTemporary = false
@Optional
@Input
String ifNoTests = 'ignore'
TestLoggingConfiguration testLoggingConfig = new TestLoggingConfiguration() TestLoggingConfiguration testLoggingConfig = new TestLoggingConfiguration()
BalancersConfiguration balancersConfig = new BalancersConfiguration(task: this) BalancersConfiguration balancersConfig = new BalancersConfiguration(task: this)
@ -172,9 +181,6 @@ class RandomizedTestingTask extends DefaultTask {
} }
} }
// TODO: add leaveTemporary
// TODO: add ifNoTests!
@TaskAction @TaskAction
void executeTests() { void executeTests() {
Map attributes = [ Map attributes = [
@ -184,7 +190,9 @@ class RandomizedTestingTask extends DefaultTask {
dir: workingDir, dir: workingDir,
tempdir: new File(workingDir, 'temp'), tempdir: new File(workingDir, 'temp'),
haltOnFailure: true, // we want to capture when a build failed, but will decide whether to rethrow later haltOnFailure: true, // we want to capture when a build failed, but will decide whether to rethrow later
shuffleOnSlave: shuffleOnSlave shuffleOnSlave: shuffleOnSlave,
leaveTemporary: leaveTemporary,
ifNoTests: ifNoTests
] ]
DefaultLogger listener = null DefaultLogger listener = null

View File

@ -322,6 +322,8 @@ class BuildPlugin implements Plugin<Project> {
return { return {
jvm "${project.javaHome}/bin/java" jvm "${project.javaHome}/bin/java"
parallelism System.getProperty('tests.jvms', 'auto') parallelism System.getProperty('tests.jvms', 'auto')
ifNoTests 'fail'
leaveTemporary true
// TODO: why are we not passing maxmemory to junit4? // TODO: why are we not passing maxmemory to junit4?
jvmArg '-Xmx' + System.getProperty('tests.heap.size', '512m') jvmArg '-Xmx' + System.getProperty('tests.heap.size', '512m')

View File

@ -1,5 +1,5 @@
elasticsearch = 3.0.0-SNAPSHOT elasticsearch = 3.0.0-SNAPSHOT
lucene = 5.4.0-snapshot-1714615 lucene = 5.4.0-snapshot-1715952
# optional dependencies # optional dependencies
spatial4j = 0.5 spatial4j = 0.5

View File

@ -275,7 +275,7 @@ public abstract class TransportReplicationAction<Request extends ReplicationRequ
@Override @Override
public void onFailure(Throwable t) { public void onFailure(Throwable t) {
if (t instanceof RetryOnReplicaException) { if (t instanceof RetryOnReplicaException) {
logger.trace("Retrying operation on replica", t); logger.trace("Retrying operation on replica, action [{}], request [{}]", t, actionName, request);
observer.waitForNextChange(new ClusterStateObserver.Listener() { observer.waitForNextChange(new ClusterStateObserver.Listener() {
@Override @Override
public void onNewClusterState(ClusterState state) { public void onNewClusterState(ClusterState state) {
@ -294,7 +294,7 @@ public abstract class TransportReplicationAction<Request extends ReplicationRequ
}); });
} else { } else {
try { try {
failReplicaIfNeeded(request.internalShardId.getIndex(), request.internalShardId.id(), t); failReplicaIfNeeded(request.internalShardId.getIndex(), request.internalShardId.id(), t, request);
} catch (Throwable unexpected) { } catch (Throwable unexpected) {
logger.error("{} unexpected error while failing replica", request.internalShardId.id(), unexpected); logger.error("{} unexpected error while failing replica", request.internalShardId.id(), unexpected);
} finally { } finally {
@ -378,7 +378,7 @@ public abstract class TransportReplicationAction<Request extends ReplicationRequ
return; return;
} }
if (primary.active() == false) { if (primary.active() == false) {
logger.trace("primary shard [{}] is not yet active, scheduling a retry.", primary.shardId()); logger.trace("primary shard [{}] is not yet active, scheduling a retry. action [{}], request [{}]", primary.shardId(), actionName, internalRequest.request);
retryBecauseUnavailable(shardIt.shardId(), "Primary shard is not active or isn't assigned to a known node."); retryBecauseUnavailable(shardIt.shardId(), "Primary shard is not active or isn't assigned to a known node.");
return; return;
} }
@ -540,7 +540,7 @@ public abstract class TransportReplicationAction<Request extends ReplicationRequ
void finishAsFailed(Throwable failure) { void finishAsFailed(Throwable failure) {
if (finished.compareAndSet(false, true)) { if (finished.compareAndSet(false, true)) {
Releasables.close(indexShardReference); Releasables.close(indexShardReference);
logger.trace("operation failed", failure); logger.trace("operation failed. action [{}], request [{}]", failure, actionName, internalRequest.request);
listener.onFailure(failure); listener.onFailure(failure);
} else { } else {
assert false : "finishAsFailed called but operation is already finished"; assert false : "finishAsFailed called but operation is already finished";
@ -548,7 +548,7 @@ public abstract class TransportReplicationAction<Request extends ReplicationRequ
} }
void finishWithUnexpectedFailure(Throwable failure) { void finishWithUnexpectedFailure(Throwable failure) {
logger.warn("unexpected error during the primary phase for action [{}]", failure, actionName); logger.warn("unexpected error during the primary phase for action [{}], request [{}]", failure, actionName, internalRequest.request);
if (finished.compareAndSet(false, true)) { if (finished.compareAndSet(false, true)) {
Releasables.close(indexShardReference); Releasables.close(indexShardReference);
listener.onFailure(failure); listener.onFailure(failure);
@ -559,7 +559,9 @@ public abstract class TransportReplicationAction<Request extends ReplicationRequ
void finishOnRemoteSuccess(Response response) { void finishOnRemoteSuccess(Response response) {
if (finished.compareAndSet(false, true)) { if (finished.compareAndSet(false, true)) {
logger.trace("operation succeeded"); if (logger.isTraceEnabled()) {
logger.trace("operation succeeded. action [{}],request [{}]", actionName, internalRequest.request);
}
listener.onResponse(response); listener.onResponse(response);
} else { } else {
assert false : "finishOnRemoteSuccess called but operation is already finished"; assert false : "finishOnRemoteSuccess called but operation is already finished";
@ -580,12 +582,14 @@ public abstract class TransportReplicationAction<Request extends ReplicationRequ
indexShardReference = getIndexShardOperationsCounter(primary.shardId()); indexShardReference = getIndexShardOperationsCounter(primary.shardId());
PrimaryOperationRequest por = new PrimaryOperationRequest(primary.id(), internalRequest.concreteIndex(), internalRequest.request()); PrimaryOperationRequest por = new PrimaryOperationRequest(primary.id(), internalRequest.concreteIndex(), internalRequest.request());
Tuple<Response, ReplicaRequest> primaryResponse = shardOperationOnPrimary(observer.observedState(), por); Tuple<Response, ReplicaRequest> primaryResponse = shardOperationOnPrimary(observer.observedState(), por);
logger.trace("operation completed on primary [{}]", primary); if (logger.isTraceEnabled()) {
logger.trace("operation completed on primary [{}], action [{}], request [{}], cluster state version [{}]", primary, actionName, por.request, observer.observedState().version());
}
replicationPhase = new ReplicationPhase(shardsIt, primaryResponse.v2(), primaryResponse.v1(), observer, primary, internalRequest, listener, indexShardReference, shardFailedTimeout); replicationPhase = new ReplicationPhase(shardsIt, primaryResponse.v2(), primaryResponse.v1(), observer, primary, internalRequest, listener, indexShardReference, shardFailedTimeout);
} catch (Throwable e) { } catch (Throwable e) {
// shard has not been allocated yet, retry it here // shard has not been allocated yet, retry it here
if (retryPrimaryException(e)) { if (retryPrimaryException(e)) {
logger.trace("had an error while performing operation on primary ({}), scheduling a retry.", e.getMessage()); logger.trace("had an error while performing operation on primary ({}, action [{}], request [{}]), scheduling a retry.", e, primary, actionName, internalRequest.request);
// We have to close here because when we retry we will increment get a new reference on index shard again and we do not want to // We have to close here because when we retry we will increment get a new reference on index shard again and we do not want to
// increment twice. // increment twice.
Releasables.close(indexShardReference); Releasables.close(indexShardReference);
@ -650,8 +654,8 @@ public abstract class TransportReplicationAction<Request extends ReplicationRequ
} }
if (sizeActive < requiredNumber) { if (sizeActive < requiredNumber) {
logger.trace("not enough active copies of shard [{}] to meet write consistency of [{}] (have {}, needed {}), scheduling a retry.", logger.trace("not enough active copies of shard [{}] to meet write consistency of [{}] (have {}, needed {}), scheduling a retry. action [{}], request [{}]",
shard.shardId(), consistencyLevel, sizeActive, requiredNumber); shard.shardId(), consistencyLevel, sizeActive, requiredNumber, actionName, internalRequest.request);
return "Not enough active copies to meet write consistency of [" + consistencyLevel + "] (have " + sizeActive + ", needed " + requiredNumber + ")."; return "Not enough active copies to meet write consistency of [" + consistencyLevel + "] (have " + sizeActive + ", needed " + requiredNumber + ").";
} else { } else {
return null; return null;
@ -670,8 +674,8 @@ public abstract class TransportReplicationAction<Request extends ReplicationRequ
return new IndexShardReference(indexShard); return new IndexShardReference(indexShard);
} }
private void failReplicaIfNeeded(String index, int shardId, Throwable t) { private void failReplicaIfNeeded(String index, int shardId, Throwable t, ReplicaRequest request) {
logger.trace("failure on replica [{}][{}]", t, index, shardId); logger.trace("failure on replica [{}][{}], action [{}], request [{}]", t, index, shardId, actionName, request);
if (ignoreReplicaException(t) == false) { if (ignoreReplicaException(t) == false) {
IndexService indexService = indicesService.indexService(index); IndexService indexService = indicesService.indexService(index);
if (indexService == null) { if (indexService == null) {
@ -833,6 +837,10 @@ public abstract class TransportReplicationAction<Request extends ReplicationRequ
*/ */
@Override @Override
protected void doRun() { protected void doRun() {
if (logger.isTraceEnabled()) {
logger.trace("replication phase started. pending [{}], action [{}], request [{}], cluster state version used [{}]", pending.get(),
actionName, replicaRequest, observer.observedState().version());
}
if (pending.get() == 0) { if (pending.get() == 0) {
doFinish(); doFinish();
return; return;
@ -889,7 +897,7 @@ public abstract class TransportReplicationAction<Request extends ReplicationRequ
@Override @Override
public void handleException(TransportException exp) { public void handleException(TransportException exp) {
logger.trace("[{}] transport failure during replica request [{}] ", exp, node, replicaRequest); logger.trace("[{}] transport failure during replica request [{}], action [{}]", exp, node, replicaRequest, actionName);
if (ignoreReplicaException(exp)) { if (ignoreReplicaException(exp)) {
onReplicaFailure(nodeId, exp); onReplicaFailure(nodeId, exp);
} else { } else {
@ -908,7 +916,7 @@ public abstract class TransportReplicationAction<Request extends ReplicationRequ
onReplicaSuccess(); onReplicaSuccess();
} catch (Throwable e) { } catch (Throwable e) {
onReplicaFailure(nodeId, e); onReplicaFailure(nodeId, e);
failReplicaIfNeeded(shard.index(), shard.id(), e); failReplicaIfNeeded(shard.index(), shard.id(), e, replicaRequest);
} }
} }
@ -924,7 +932,7 @@ public abstract class TransportReplicationAction<Request extends ReplicationRequ
} }
}); });
} catch (Throwable e) { } catch (Throwable e) {
failReplicaIfNeeded(shard.index(), shard.id(), e); failReplicaIfNeeded(shard.index(), shard.id(), e, replicaRequest);
onReplicaFailure(nodeId, e); onReplicaFailure(nodeId, e);
} }
} }

View File

@ -190,6 +190,8 @@ public class TransportUpdateAction extends TransportInstanceSingleOperationActio
e = ExceptionsHelper.unwrapCause(e); e = ExceptionsHelper.unwrapCause(e);
if (e instanceof VersionConflictEngineException) { if (e instanceof VersionConflictEngineException) {
if (retryCount < request.retryOnConflict()) { if (retryCount < request.retryOnConflict()) {
logger.trace("Retry attempt [{}] of [{}] on version conflict on [{}][{}][{}]",
retryCount + 1, request.retryOnConflict(), request.index(), request.shardId(), request.id());
threadPool.executor(executor()).execute(new ActionRunnable<UpdateResponse>(listener) { threadPool.executor(executor()).execute(new ActionRunnable<UpdateResponse>(listener) {
@Override @Override
protected void doRun() { protected void doRun() {

View File

@ -26,12 +26,12 @@ import org.elasticsearch.cluster.routing.UnassignedInfo;
import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.analysis.AnalysisService; import org.elasticsearch.index.analysis.AnalysisService;
import org.elasticsearch.index.analysis.NamedAnalyzer; import org.elasticsearch.index.analysis.NamedAnalyzer;
import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.similarity.SimilarityService; import org.elasticsearch.index.similarity.SimilarityService;
import org.elasticsearch.indices.mapper.MapperRegistry;
import java.util.Collections; import java.util.Collections;
import java.util.Set; import java.util.Set;
@ -48,9 +48,13 @@ import static org.elasticsearch.common.util.set.Sets.newHashSet;
* are restored from a repository. * are restored from a repository.
*/ */
public class MetaDataIndexUpgradeService extends AbstractComponent { public class MetaDataIndexUpgradeService extends AbstractComponent {
private final MapperRegistry mapperRegistry;
@Inject @Inject
public MetaDataIndexUpgradeService(Settings settings) { public MetaDataIndexUpgradeService(Settings settings, MapperRegistry mapperRegistry) {
super(settings); super(settings);
this.mapperRegistry = mapperRegistry;
} }
/** /**
@ -218,7 +222,7 @@ public class MetaDataIndexUpgradeService extends AbstractComponent {
SimilarityService similarityService = new SimilarityService(indexSettings, Collections.EMPTY_MAP); SimilarityService similarityService = new SimilarityService(indexSettings, Collections.EMPTY_MAP);
try (AnalysisService analysisService = new FakeAnalysisService(indexSettings)) { try (AnalysisService analysisService = new FakeAnalysisService(indexSettings)) {
try (MapperService mapperService = new MapperService(indexSettings, analysisService, similarityService)) { try (MapperService mapperService = new MapperService(indexSettings, analysisService, similarityService, mapperRegistry)) {
for (ObjectCursor<MappingMetaData> cursor : indexMetaData.getMappings().values()) { for (ObjectCursor<MappingMetaData> cursor : indexMetaData.getMappings().values()) {
MappingMetaData mappingMetaData = cursor.value; MappingMetaData mappingMetaData = cursor.value;
mapperService.merge(mappingMetaData.type(), mappingMetaData.source(), false, false); mapperService.merge(mappingMetaData.type(), mappingMetaData.source(), false, false);

View File

@ -19,11 +19,14 @@
package org.elasticsearch.cluster.routing; package org.elasticsearch.cluster.routing;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.gateway.CorruptStateException;
import java.io.IOException; import java.io.IOException;
@ -37,8 +40,11 @@ import java.io.IOException;
* behavior to how ShardRouting#currentNodeId is used. * behavior to how ShardRouting#currentNodeId is used.
*/ */
public class AllocationId implements ToXContent { public class AllocationId implements ToXContent {
private static final String ID_KEY = "id";
private static final String RELOCATION_ID_KEY = "relocation_id";
private final String id; private final String id;
@Nullable
private final String relocationId; private final String relocationId;
AllocationId(StreamInput in) throws IOException { AllocationId(StreamInput in) throws IOException {
@ -148,12 +154,45 @@ public class AllocationId implements ToXContent {
@Override @Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject("allocation_id"); builder.startObject();
builder.field("id", id); builder.field(ID_KEY, id);
if (relocationId != null) { if (relocationId != null) {
builder.field("relocation_id", relocationId); builder.field(RELOCATION_ID_KEY, relocationId);
} }
builder.endObject(); builder.endObject();
return builder; return builder;
} }
public static AllocationId fromXContent(XContentParser parser) throws IOException {
XContentParser.Token token = parser.currentToken();
if (token == null) { // fresh parser? move to the first real token under object
token = parser.nextToken();
}
assert token == XContentParser.Token.START_OBJECT;
String id = null;
String relocationId = null;
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token.isValue()) {
if (ID_KEY.equals(currentFieldName)) {
id = parser.text();
} else if (RELOCATION_ID_KEY.equals(currentFieldName)) {
relocationId = parser.text();
} else {
throw new CorruptStateException("unexpected field in allocation id [" + currentFieldName + "]");
}
} else {
throw new CorruptStateException("unexpected token in allocation id [" + token.name() + "]");
}
}
if (id == null) {
throw new CorruptStateException("missing value for [id] in allocation id");
}
return new AllocationId(id, relocationId);
}
} }

View File

@ -55,7 +55,7 @@ public class RoutingService extends AbstractLifecycleComponent<RoutingService> i
private final AllocationService allocationService; private final AllocationService allocationService;
private AtomicBoolean rerouting = new AtomicBoolean(); private AtomicBoolean rerouting = new AtomicBoolean();
private volatile long minDelaySettingAtLastScheduling = Long.MAX_VALUE; private volatile long minDelaySettingAtLastSchedulingNanos = Long.MAX_VALUE;
private volatile ScheduledFuture registeredNextDelayFuture; private volatile ScheduledFuture registeredNextDelayFuture;
@Inject @Inject
@ -100,14 +100,14 @@ public class RoutingService extends AbstractLifecycleComponent<RoutingService> i
// Figure out if an existing scheduled reroute is good enough or whether we need to cancel and reschedule. // Figure out if an existing scheduled reroute is good enough or whether we need to cancel and reschedule.
// If the minimum of the currently relevant delay settings is larger than something we scheduled in the past, // If the minimum of the currently relevant delay settings is larger than something we scheduled in the past,
// we are guaranteed that the planned schedule will happen before any of the current shard delays are expired. // we are guaranteed that the planned schedule will happen before any of the current shard delays are expired.
long minDelaySetting = UnassignedInfo.findSmallestDelayedAllocationSetting(settings, event.state()); long minDelaySetting = UnassignedInfo.findSmallestDelayedAllocationSettingNanos(settings, event.state());
if (minDelaySetting <= 0) { if (minDelaySetting <= 0) {
logger.trace("no need to schedule reroute - no delayed unassigned shards, minDelaySetting [{}], scheduled [{}]", minDelaySetting, minDelaySettingAtLastScheduling); logger.trace("no need to schedule reroute - no delayed unassigned shards, minDelaySetting [{}], scheduled [{}]", minDelaySetting, minDelaySettingAtLastSchedulingNanos);
minDelaySettingAtLastScheduling = Long.MAX_VALUE; minDelaySettingAtLastSchedulingNanos = Long.MAX_VALUE;
FutureUtils.cancel(registeredNextDelayFuture); FutureUtils.cancel(registeredNextDelayFuture);
} else if (minDelaySetting < minDelaySettingAtLastScheduling) { } else if (minDelaySetting < minDelaySettingAtLastSchedulingNanos) {
FutureUtils.cancel(registeredNextDelayFuture); FutureUtils.cancel(registeredNextDelayFuture);
minDelaySettingAtLastScheduling = minDelaySetting; minDelaySettingAtLastSchedulingNanos = minDelaySetting;
TimeValue nextDelay = TimeValue.timeValueNanos(UnassignedInfo.findNextDelayedAllocationIn(event.state())); TimeValue nextDelay = TimeValue.timeValueNanos(UnassignedInfo.findNextDelayedAllocationIn(event.state()));
assert nextDelay.nanos() > 0 : "next delay must be non 0 as minDelaySetting is [" + minDelaySetting + "]"; assert nextDelay.nanos() > 0 : "next delay must be non 0 as minDelaySetting is [" + minDelaySetting + "]";
logger.info("delaying allocation for [{}] unassigned shards, next check in [{}]", logger.info("delaying allocation for [{}] unassigned shards, next check in [{}]",
@ -115,25 +115,25 @@ public class RoutingService extends AbstractLifecycleComponent<RoutingService> i
registeredNextDelayFuture = threadPool.schedule(nextDelay, ThreadPool.Names.SAME, new AbstractRunnable() { registeredNextDelayFuture = threadPool.schedule(nextDelay, ThreadPool.Names.SAME, new AbstractRunnable() {
@Override @Override
protected void doRun() throws Exception { protected void doRun() throws Exception {
minDelaySettingAtLastScheduling = Long.MAX_VALUE; minDelaySettingAtLastSchedulingNanos = Long.MAX_VALUE;
reroute("assign delayed unassigned shards"); reroute("assign delayed unassigned shards");
} }
@Override @Override
public void onFailure(Throwable t) { public void onFailure(Throwable t) {
logger.warn("failed to schedule/execute reroute post unassigned shard", t); logger.warn("failed to schedule/execute reroute post unassigned shard", t);
minDelaySettingAtLastScheduling = Long.MAX_VALUE; minDelaySettingAtLastSchedulingNanos = Long.MAX_VALUE;
} }
}); });
} else { } else {
logger.trace("no need to schedule reroute - current schedule reroute is enough. minDelaySetting [{}], scheduled [{}]", minDelaySetting, minDelaySettingAtLastScheduling); logger.trace("no need to schedule reroute - current schedule reroute is enough. minDelaySetting [{}], scheduled [{}]", minDelaySetting, minDelaySettingAtLastSchedulingNanos);
} }
} }
} }
// visible for testing // visible for testing
long getMinDelaySettingAtLastScheduling() { long getMinDelaySettingAtLastSchedulingNanos() {
return this.minDelaySettingAtLastScheduling; return this.minDelaySettingAtLastSchedulingNanos;
} }
// visible for testing // visible for testing

View File

@ -188,7 +188,6 @@ public class RoutingTable implements Iterable<IndexRoutingTable>, Diffable<Routi
private static Predicate<ShardRouting> ACTIVE_PREDICATE = shardRouting -> shardRouting.active(); private static Predicate<ShardRouting> ACTIVE_PREDICATE = shardRouting -> shardRouting.active();
private static Predicate<ShardRouting> ASSIGNED_PREDICATE = shardRouting -> shardRouting.assignedToNode(); private static Predicate<ShardRouting> ASSIGNED_PREDICATE = shardRouting -> shardRouting.assignedToNode();
// TODO: replace with JDK 8 native java.util.function.Predicate
private GroupShardsIterator allSatisfyingPredicateShardsGrouped(String[] indices, boolean includeEmpty, boolean includeRelocationTargets, Predicate<ShardRouting> predicate) { private GroupShardsIterator allSatisfyingPredicateShardsGrouped(String[] indices, boolean includeEmpty, boolean includeRelocationTargets, Predicate<ShardRouting> predicate) {
// use list here since we need to maintain identity across shards // use list here since we need to maintain identity across shards
ArrayList<ShardIterator> set = new ArrayList<>(); ArrayList<ShardIterator> set = new ArrayList<>();
@ -222,7 +221,6 @@ public class RoutingTable implements Iterable<IndexRoutingTable>, Diffable<Routi
return allShardsSatisfyingPredicate(indices, shardRouting -> true, true); return allShardsSatisfyingPredicate(indices, shardRouting -> true, true);
} }
// TODO: replace with JDK 8 native java.util.function.Predicate
private ShardsIterator allShardsSatisfyingPredicate(String[] indices, Predicate<ShardRouting> predicate, boolean includeRelocationTargets) { private ShardsIterator allShardsSatisfyingPredicate(String[] indices, Predicate<ShardRouting> predicate, boolean includeRelocationTargets) {
// use list here since we need to maintain identity across shards // use list here since we need to maintain identity across shards
List<ShardRouting> shards = new ArrayList<>(); List<ShardRouting> shards = new ArrayList<>();

View File

@ -716,6 +716,7 @@ public final class ShardRouting implements Streamable, ToXContent {
restoreSource().toXContent(builder, params); restoreSource().toXContent(builder, params);
} }
if (allocationId != null) { if (allocationId != null) {
builder.field("allocation_id");
allocationId.toXContent(builder, params); allocationId.toXContent(builder, params);
} }
if (unassignedInfo != null) { if (unassignedInfo != null) {

View File

@ -34,7 +34,6 @@ import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import java.io.IOException; import java.io.IOException;
import java.util.concurrent.TimeUnit;
/** /**
* Holds additional information as to why the shard is in unassigned state. * Holds additional information as to why the shard is in unassigned state.
@ -110,18 +109,27 @@ public class UnassignedInfo implements ToXContent, Writeable<UnassignedInfo> {
private final String message; private final String message;
private final Throwable failure; private final Throwable failure;
/**
* creates an UnassingedInfo object based **current** time
*
* @param reason the cause for making this shard unassigned. See {@link Reason} for more information.
* @param message more information about cause.
**/
public UnassignedInfo(Reason reason, String message) { public UnassignedInfo(Reason reason, String message) {
this(reason, System.currentTimeMillis(), System.nanoTime(), message, null); this(reason, message, null, System.nanoTime(), System.currentTimeMillis());
} }
public UnassignedInfo(Reason reason, @Nullable String message, @Nullable Throwable failure) { /**
this(reason, System.currentTimeMillis(), System.nanoTime(), message, failure); * @param reason the cause for making this shard unassigned. See {@link Reason} for more information.
} * @param message more information about cause.
* @param failure the shard level failure that caused this shard to be unassigned, if exists.
private UnassignedInfo(Reason reason, long unassignedTimeMillis, long timestampNanos, String message, Throwable failure) { * @param unassignedTimeNanos the time to use as the base for any delayed re-assignment calculation
* @param unassignedTimeMillis the time of unassignment used to display to in our reporting.
*/
public UnassignedInfo(Reason reason, @Nullable String message, @Nullable Throwable failure, long unassignedTimeNanos, long unassignedTimeMillis) {
this.reason = reason; this.reason = reason;
this.unassignedTimeMillis = unassignedTimeMillis; this.unassignedTimeMillis = unassignedTimeMillis;
this.unassignedTimeNanos = timestampNanos; this.unassignedTimeNanos = unassignedTimeNanos;
this.message = message; this.message = message;
this.failure = failure; this.failure = failure;
assert !(message == null && failure != null) : "provide a message if a failure exception is provided"; assert !(message == null && failure != null) : "provide a message if a failure exception is provided";
@ -201,14 +209,14 @@ public class UnassignedInfo implements ToXContent, Writeable<UnassignedInfo> {
} }
/** /**
* The allocation delay value in milliseconds associated with the index (defaulting to node settings if not set). * The allocation delay value in nano seconds associated with the index (defaulting to node settings if not set).
*/ */
public long getAllocationDelayTimeoutSetting(Settings settings, Settings indexSettings) { public long getAllocationDelayTimeoutSettingNanos(Settings settings, Settings indexSettings) {
if (reason != Reason.NODE_LEFT) { if (reason != Reason.NODE_LEFT) {
return 0; return 0;
} }
TimeValue delayTimeout = indexSettings.getAsTime(INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING, settings.getAsTime(INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING, DEFAULT_DELAYED_NODE_LEFT_TIMEOUT)); TimeValue delayTimeout = indexSettings.getAsTime(INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING, settings.getAsTime(INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING, DEFAULT_DELAYED_NODE_LEFT_TIMEOUT));
return Math.max(0l, delayTimeout.millis()); return Math.max(0l, delayTimeout.nanos());
} }
/** /**
@ -221,18 +229,17 @@ public class UnassignedInfo implements ToXContent, Writeable<UnassignedInfo> {
/** /**
* Updates delay left based on current time (in nanoseconds) and index/node settings. * Updates delay left based on current time (in nanoseconds) and index/node settings.
* Should only be called from ReplicaShardAllocator. *
* @return updated delay in nanoseconds * @return updated delay in nanoseconds
*/ */
public long updateDelay(long nanoTimeNow, Settings settings, Settings indexSettings) { public long updateDelay(long nanoTimeNow, Settings settings, Settings indexSettings) {
long delayTimeoutMillis = getAllocationDelayTimeoutSetting(settings, indexSettings); long delayTimeoutNanos = getAllocationDelayTimeoutSettingNanos(settings, indexSettings);
final long newComputedLeftDelayNanos; final long newComputedLeftDelayNanos;
if (delayTimeoutMillis == 0l) { if (delayTimeoutNanos == 0l) {
newComputedLeftDelayNanos = 0l; newComputedLeftDelayNanos = 0l;
} else { } else {
assert nanoTimeNow >= unassignedTimeNanos; assert nanoTimeNow >= unassignedTimeNanos;
long delayTimeoutNanos = TimeUnit.NANOSECONDS.convert(delayTimeoutMillis, TimeUnit.MILLISECONDS); newComputedLeftDelayNanos = Math.max(0L, delayTimeoutNanos - (nanoTimeNow - unassignedTimeNanos));
newComputedLeftDelayNanos = Math.max(0l, delayTimeoutNanos - (nanoTimeNow - unassignedTimeNanos));
} }
lastComputedLeftDelayNanos = newComputedLeftDelayNanos; lastComputedLeftDelayNanos = newComputedLeftDelayNanos;
return newComputedLeftDelayNanos; return newComputedLeftDelayNanos;
@ -255,21 +262,21 @@ public class UnassignedInfo implements ToXContent, Writeable<UnassignedInfo> {
} }
/** /**
* Finds the smallest delay expiration setting in milliseconds of all unassigned shards that are still delayed. Returns 0 if there are none. * Finds the smallest delay expiration setting in nanos of all unassigned shards that are still delayed. Returns 0 if there are none.
*/ */
public static long findSmallestDelayedAllocationSetting(Settings settings, ClusterState state) { public static long findSmallestDelayedAllocationSettingNanos(Settings settings, ClusterState state) {
long nextDelaySetting = Long.MAX_VALUE; long minDelaySetting = Long.MAX_VALUE;
for (ShardRouting shard : state.routingTable().shardsWithState(ShardRoutingState.UNASSIGNED)) { for (ShardRouting shard : state.routingTable().shardsWithState(ShardRoutingState.UNASSIGNED)) {
if (shard.primary() == false) { if (shard.primary() == false) {
IndexMetaData indexMetaData = state.metaData().index(shard.getIndex()); IndexMetaData indexMetaData = state.metaData().index(shard.getIndex());
long leftDelayNanos = shard.unassignedInfo().getLastComputedLeftDelayNanos(); boolean delayed = shard.unassignedInfo().getLastComputedLeftDelayNanos() > 0;
long delayTimeoutSetting = shard.unassignedInfo().getAllocationDelayTimeoutSetting(settings, indexMetaData.getSettings()); long delayTimeoutSetting = shard.unassignedInfo().getAllocationDelayTimeoutSettingNanos(settings, indexMetaData.getSettings());
if (leftDelayNanos > 0 && delayTimeoutSetting > 0 && delayTimeoutSetting < nextDelaySetting) { if (delayed && delayTimeoutSetting > 0 && delayTimeoutSetting < minDelaySetting) {
nextDelaySetting = delayTimeoutSetting; minDelaySetting = delayTimeoutSetting;
} }
} }
} }
return nextDelaySetting == Long.MAX_VALUE ? 0l : nextDelaySetting; return minDelaySetting == Long.MAX_VALUE ? 0l : minDelaySetting;
} }
@ -320,14 +327,24 @@ public class UnassignedInfo implements ToXContent, Writeable<UnassignedInfo> {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) {
if (o == null || getClass() != o.getClass()) return false; return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UnassignedInfo that = (UnassignedInfo) o; UnassignedInfo that = (UnassignedInfo) o;
if (unassignedTimeMillis != that.unassignedTimeMillis) return false; if (unassignedTimeMillis != that.unassignedTimeMillis) {
if (reason != that.reason) return false; return false;
if (message != null ? !message.equals(that.message) : that.message != null) return false; }
if (reason != that.reason) {
return false;
}
if (message != null ? !message.equals(that.message) : that.message != null) {
return false;
}
return !(failure != null ? !failure.equals(that.failure) : that.failure != null); return !(failure != null ? !failure.equals(that.failure) : that.failure != null);
} }

View File

@ -22,16 +22,12 @@ package org.elasticsearch.cluster.routing.allocation;
import com.carrotsearch.hppc.cursors.ObjectCursor; import com.carrotsearch.hppc.cursors.ObjectCursor;
import org.elasticsearch.cluster.ClusterInfoService; import org.elasticsearch.cluster.ClusterInfoService;
import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.health.ClusterStateHealth;
import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.cluster.health.ClusterStateHealth;
import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.IndexRoutingTable; import org.elasticsearch.cluster.routing.*;
import org.elasticsearch.cluster.routing.RoutingNode;
import org.elasticsearch.cluster.routing.RoutingNodes;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.UnassignedInfo;
import org.elasticsearch.cluster.routing.allocation.allocator.ShardsAllocators; import org.elasticsearch.cluster.routing.allocation.allocator.ShardsAllocators;
import org.elasticsearch.cluster.routing.allocation.command.AllocationCommands; import org.elasticsearch.cluster.routing.allocation.command.AllocationCommands;
import org.elasticsearch.cluster.routing.allocation.decider.AllocationDeciders; import org.elasticsearch.cluster.routing.allocation.decider.AllocationDeciders;
@ -43,9 +39,7 @@ import org.elasticsearch.common.settings.Settings;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -119,7 +113,8 @@ public class AllocationService extends AbstractComponent {
FailedRerouteAllocation allocation = new FailedRerouteAllocation(allocationDeciders, routingNodes, clusterState.nodes(), failedShards, clusterInfoService.getClusterInfo()); FailedRerouteAllocation allocation = new FailedRerouteAllocation(allocationDeciders, routingNodes, clusterState.nodes(), failedShards, clusterInfoService.getClusterInfo());
boolean changed = false; boolean changed = false;
for (FailedRerouteAllocation.FailedShard failedShard : failedShards) { for (FailedRerouteAllocation.FailedShard failedShard : failedShards) {
changed |= applyFailedShard(allocation, failedShard.shard, true, new UnassignedInfo(UnassignedInfo.Reason.ALLOCATION_FAILED, failedShard.message, failedShard.failure)); changed |= applyFailedShard(allocation, failedShard.shard, true, new UnassignedInfo(UnassignedInfo.Reason.ALLOCATION_FAILED, failedShard.message, failedShard.failure,
System.nanoTime(), System.currentTimeMillis()));
} }
if (!changed) { if (!changed) {
return new RoutingAllocation.Result(false, clusterState.routingTable()); return new RoutingAllocation.Result(false, clusterState.routingTable());
@ -163,7 +158,7 @@ public class AllocationService extends AbstractComponent {
// we don't shuffle the unassigned shards here, to try and get as close as possible to // we don't shuffle the unassigned shards here, to try and get as close as possible to
// a consistent result of the effect the commands have on the routing // a consistent result of the effect the commands have on the routing
// this allows systems to dry run the commands, see the resulting cluster state, and act on it // this allows systems to dry run the commands, see the resulting cluster state, and act on it
RoutingAllocation allocation = new RoutingAllocation(allocationDeciders, routingNodes, clusterState.nodes(), clusterInfoService.getClusterInfo()); RoutingAllocation allocation = new RoutingAllocation(allocationDeciders, routingNodes, clusterState.nodes(), clusterInfoService.getClusterInfo(), currentNanoTime());
// don't short circuit deciders, we want a full explanation // don't short circuit deciders, we want a full explanation
allocation.debugDecision(true); allocation.debugDecision(true);
// we ignore disable allocation, because commands are explicit // we ignore disable allocation, because commands are explicit
@ -202,7 +197,7 @@ public class AllocationService extends AbstractComponent {
RoutingNodes routingNodes = getMutableRoutingNodes(clusterState); RoutingNodes routingNodes = getMutableRoutingNodes(clusterState);
// shuffle the unassigned nodes, just so we won't have things like poison failed shards // shuffle the unassigned nodes, just so we won't have things like poison failed shards
routingNodes.unassigned().shuffle(); routingNodes.unassigned().shuffle();
RoutingAllocation allocation = new RoutingAllocation(allocationDeciders, routingNodes, clusterState.nodes(), clusterInfoService.getClusterInfo()); RoutingAllocation allocation = new RoutingAllocation(allocationDeciders, routingNodes, clusterState.nodes(), clusterInfoService.getClusterInfo(), currentNanoTime());
allocation.debugDecision(debug); allocation.debugDecision(debug);
if (!reroute(allocation)) { if (!reroute(allocation)) {
return new RoutingAllocation.Result(false, clusterState.routingTable()); return new RoutingAllocation.Result(false, clusterState.routingTable());
@ -239,6 +234,8 @@ public class AllocationService extends AbstractComponent {
// now allocate all the unassigned to available nodes // now allocate all the unassigned to available nodes
if (allocation.routingNodes().unassigned().size() > 0) { if (allocation.routingNodes().unassigned().size() > 0) {
updateLeftDelayOfUnassignedShards(allocation, settings);
changed |= shardsAllocators.allocateUnassigned(allocation); changed |= shardsAllocators.allocateUnassigned(allocation);
} }
@ -251,6 +248,15 @@ public class AllocationService extends AbstractComponent {
return changed; return changed;
} }
// public for testing
public static void updateLeftDelayOfUnassignedShards(RoutingAllocation allocation, Settings settings) {
for (ShardRouting shardRouting : allocation.routingNodes().unassigned()) {
final MetaData metaData = allocation.metaData();
final IndexMetaData indexMetaData = metaData.index(shardRouting.index());
shardRouting.unassignedInfo().updateDelay(allocation.getCurrentNanoTime(), settings, indexMetaData.getSettings());
}
}
private boolean moveShards(RoutingAllocation allocation) { private boolean moveShards(RoutingAllocation allocation) {
boolean changed = false; boolean changed = false;
@ -312,7 +318,9 @@ public class AllocationService extends AbstractComponent {
} }
} }
for (ShardRouting shardToFail : shardsToFail) { for (ShardRouting shardToFail : shardsToFail) {
changed |= applyFailedShard(allocation, shardToFail, false, new UnassignedInfo(UnassignedInfo.Reason.ALLOCATION_FAILED, "primary failed while replica initializing")); changed |= applyFailedShard(allocation, shardToFail, false,
new UnassignedInfo(UnassignedInfo.Reason.ALLOCATION_FAILED, "primary failed while replica initializing",
null, allocation.getCurrentNanoTime(), System.currentTimeMillis()));
} }
// now, go over and elect a new primary if possible, not, from this code block on, if one is elected, // now, go over and elect a new primary if possible, not, from this code block on, if one is elected,
@ -372,8 +380,9 @@ public class AllocationService extends AbstractComponent {
} }
changed = true; changed = true;
// now, go over all the shards routing on the node, and fail them // now, go over all the shards routing on the node, and fail them
UnassignedInfo unassignedInfo = new UnassignedInfo(UnassignedInfo.Reason.NODE_LEFT, "node_left[" + node.nodeId() + "]");
for (ShardRouting shardRouting : node.copyShards()) { for (ShardRouting shardRouting : node.copyShards()) {
UnassignedInfo unassignedInfo = new UnassignedInfo(UnassignedInfo.Reason.NODE_LEFT, "node_left[" + node.nodeId() + "]", null,
allocation.getCurrentNanoTime(), System.currentTimeMillis());
applyFailedShard(allocation, shardRouting, false, unassignedInfo); applyFailedShard(allocation, shardRouting, false, unassignedInfo);
} }
// its a dead node, remove it, note, its important to remove it *after* we apply failed shard // its a dead node, remove it, note, its important to remove it *after* we apply failed shard
@ -531,4 +540,9 @@ public class AllocationService extends AbstractComponent {
RoutingNodes routingNodes = new RoutingNodes(clusterState, false); // this is a costly operation - only call this once! RoutingNodes routingNodes = new RoutingNodes(clusterState, false); // this is a costly operation - only call this once!
return routingNodes; return routingNodes;
} }
/** ovrride this to control time based decisions during allocation */
protected long currentNanoTime() {
return System.nanoTime();
}
} }

View File

@ -58,7 +58,7 @@ public class FailedRerouteAllocation extends RoutingAllocation {
private final List<FailedShard> failedShards; private final List<FailedShard> failedShards;
public FailedRerouteAllocation(AllocationDeciders deciders, RoutingNodes routingNodes, DiscoveryNodes nodes, List<FailedShard> failedShards, ClusterInfo clusterInfo) { public FailedRerouteAllocation(AllocationDeciders deciders, RoutingNodes routingNodes, DiscoveryNodes nodes, List<FailedShard> failedShards, ClusterInfo clusterInfo) {
super(deciders, routingNodes, nodes, clusterInfo); super(deciders, routingNodes, nodes, clusterInfo, System.nanoTime());
this.failedShards = failedShards; this.failedShards = failedShards;
} }

View File

@ -120,19 +120,27 @@ public class RoutingAllocation {
private boolean hasPendingAsyncFetch = false; private boolean hasPendingAsyncFetch = false;
private final long currentNanoTime;
/** /**
* Creates a new {@link RoutingAllocation} * Creates a new {@link RoutingAllocation}
* * @param deciders {@link AllocationDeciders} to used to make decisions for routing allocations
* @param deciders {@link AllocationDeciders} to used to make decisions for routing allocations * @param routingNodes Routing nodes in the current cluster
* @param routingNodes Routing nodes in the current cluster
* @param nodes TODO: Documentation * @param nodes TODO: Documentation
* @param currentNanoTime the nano time to use for all delay allocation calculation (typically {@link System#nanoTime()})
*/ */
public RoutingAllocation(AllocationDeciders deciders, RoutingNodes routingNodes, DiscoveryNodes nodes, ClusterInfo clusterInfo) { public RoutingAllocation(AllocationDeciders deciders, RoutingNodes routingNodes, DiscoveryNodes nodes, ClusterInfo clusterInfo, long currentNanoTime) {
this.deciders = deciders; this.deciders = deciders;
this.routingNodes = routingNodes; this.routingNodes = routingNodes;
this.nodes = nodes; this.nodes = nodes;
this.clusterInfo = clusterInfo; this.clusterInfo = clusterInfo;
this.currentNanoTime = currentNanoTime;
}
/** returns the nano time captured at the beginning of the allocation. used to make sure all time based decisions are aligned */
public long getCurrentNanoTime() {
return currentNanoTime;
} }
/** /**

View File

@ -36,7 +36,7 @@ public class StartedRerouteAllocation extends RoutingAllocation {
private final List<? extends ShardRouting> startedShards; private final List<? extends ShardRouting> startedShards;
public StartedRerouteAllocation(AllocationDeciders deciders, RoutingNodes routingNodes, DiscoveryNodes nodes, List<? extends ShardRouting> startedShards, ClusterInfo clusterInfo) { public StartedRerouteAllocation(AllocationDeciders deciders, RoutingNodes routingNodes, DiscoveryNodes nodes, List<? extends ShardRouting> startedShards, ClusterInfo clusterInfo) {
super(deciders, routingNodes, nodes, clusterInfo); super(deciders, routingNodes, nodes, clusterInfo, System.nanoTime());
this.startedShards = startedShards; this.startedShards = startedShards;
} }

View File

@ -19,8 +19,8 @@
package org.elasticsearch.cluster.routing.allocation.allocator; package org.elasticsearch.cluster.routing.allocation.allocator;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.RoutingNode; import org.elasticsearch.cluster.routing.RoutingNode;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.allocation.FailedRerouteAllocation; import org.elasticsearch.cluster.routing.allocation.FailedRerouteAllocation;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation; import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.cluster.routing.allocation.StartedRerouteAllocation; import org.elasticsearch.cluster.routing.allocation.StartedRerouteAllocation;
@ -74,6 +74,10 @@ public class ShardsAllocators extends AbstractComponent implements ShardsAllocat
return changed; return changed;
} }
protected long nanoTime() {
return System.nanoTime();
}
@Override @Override
public boolean rebalance(RoutingAllocation allocation) { public boolean rebalance(RoutingAllocation allocation) {
if (allocation.hasPendingAsyncFetch() == false) { if (allocation.hasPendingAsyncFetch() == false) {

View File

@ -229,7 +229,8 @@ public class AllocateAllocationCommand implements AllocationCommand {
// it was index creation // it was index creation
if (unassigned.primary() && unassigned.unassignedInfo().getReason() != UnassignedInfo.Reason.INDEX_CREATED) { if (unassigned.primary() && unassigned.unassignedInfo().getReason() != UnassignedInfo.Reason.INDEX_CREATED) {
unassigned.updateUnassignedInfo(new UnassignedInfo(UnassignedInfo.Reason.INDEX_CREATED, unassigned.updateUnassignedInfo(new UnassignedInfo(UnassignedInfo.Reason.INDEX_CREATED,
"force allocation from previous reason " + unassigned.unassignedInfo().getReason() + ", " + unassigned.unassignedInfo().getMessage(), unassigned.unassignedInfo().getFailure())); "force allocation from previous reason " + unassigned.unassignedInfo().getReason() + ", " + unassigned.unassignedInfo().getMessage(),
unassigned.unassignedInfo().getFailure(), System.nanoTime(), System.currentTimeMillis()));
} }
it.initialize(routingNode.nodeId(), unassigned.version(), allocation.clusterInfo().getShardSize(unassigned, ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE)); it.initialize(routingNode.nodeId(), unassigned.version(), allocation.clusterInfo().getShardSize(unassigned, ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE));
break; break;

View File

@ -21,7 +21,10 @@ package org.elasticsearch.cluster.routing.allocation.command;
import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.*; import org.elasticsearch.cluster.routing.RoutingNode;
import org.elasticsearch.cluster.routing.RoutingNodes;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.UnassignedInfo;
import org.elasticsearch.cluster.routing.allocation.RerouteExplanation; import org.elasticsearch.cluster.routing.allocation.RerouteExplanation;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation; import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.cluster.routing.allocation.decider.Decision; import org.elasticsearch.cluster.routing.allocation.decider.Decision;
@ -34,7 +37,6 @@ import org.elasticsearch.index.shard.ShardId;
import java.io.IOException; import java.io.IOException;
import static org.elasticsearch.cluster.routing.ShardRoutingState.INITIALIZING;
import static org.elasticsearch.cluster.routing.ShardRoutingState.RELOCATING; import static org.elasticsearch.cluster.routing.ShardRoutingState.RELOCATING;
/** /**

View File

@ -0,0 +1,116 @@
/*
* 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.common.network;
import java.util.Arrays;
import java.util.Locale;
import java.util.Objects;
public final class Cidrs {
private Cidrs() {
}
/**
* Parses an IPv4 address block in CIDR notation into a pair of
* longs representing the bottom and top of the address block
*
* @param cidr an address block in CIDR notation a.b.c.d/n
* @return array representing the address block
* @throws IllegalArgumentException if the cidr can not be parsed
*/
public static long[] cidrMaskToMinMax(String cidr) {
Objects.requireNonNull(cidr, "cidr");
String[] fields = cidr.split("/");
if (fields.length != 2) {
throw new IllegalArgumentException(
String.format(Locale.ROOT, "invalid IPv4/CIDR; expected [a.b.c.d, e] but was [%s] after splitting on \"/\" in [%s]", Arrays.toString(fields), cidr)
);
}
// do not try to parse IPv4-mapped IPv6 address
if (fields[0].contains(":")) {
throw new IllegalArgumentException(
String.format(Locale.ROOT, "invalid IPv4/CIDR; expected [a.b.c.d, e] where a, b, c, d are decimal octets but was [%s] after splitting on \"/\" in [%s]", Arrays.toString(fields), cidr)
);
}
byte[] addressBytes;
try {
addressBytes = InetAddresses.forString(fields[0]).getAddress();
} catch (Throwable t) {
throw new IllegalArgumentException(
String.format(Locale.ROOT, "invalid IPv4/CIDR; unable to parse [%s] as an IP address literal", fields[0]), t
);
}
long accumulator =
((addressBytes[0] & 0xFFL) << 24) +
((addressBytes[1] & 0xFFL) << 16) +
((addressBytes[2] & 0xFFL) << 8) +
((addressBytes[3] & 0xFFL));
int networkMask;
try {
networkMask = Integer.parseInt(fields[1]);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(
String.format(Locale.ROOT, "invalid IPv4/CIDR; invalid network mask [%s] in [%s]", fields[1], cidr),
e
);
}
if (networkMask < 0 || networkMask > 32) {
throw new IllegalArgumentException(
String.format(Locale.ROOT, "invalid IPv4/CIDR; invalid network mask [%s], out of range in [%s]", fields[1], cidr)
);
}
long blockSize = 1L << (32 - networkMask);
// validation
if ((accumulator & (blockSize - 1)) != 0) {
throw new IllegalArgumentException(
String.format(
Locale.ROOT,
"invalid IPv4/CIDR; invalid address/network mask combination in [%s]; perhaps [%s] was intended?",
cidr,
octetsToCIDR(longToOctets(accumulator - (accumulator & (blockSize - 1))), networkMask)
)
);
}
return new long[] { accumulator, accumulator + blockSize };
}
static int[] longToOctets(long value) {
assert value >= 0 && value <= (1L << 32) : value;
int[] octets = new int[4];
octets[0] = (int)((value >> 24) & 0xFF);
octets[1] = (int)((value >> 16) & 0xFF);
octets[2] = (int)((value >> 8) & 0xFF);
octets[3] = (int)(value & 0xFF);
return octets;
}
static String octetsToString(int[] octets) {
assert octets != null;
assert octets.length == 4;
return String.format(Locale.ROOT, "%d.%d.%d.%d", octets[0], octets[1], octets[2], octets[3]);
}
static String octetsToCIDR(int[] octets, int networkMask) {
assert octets != null;
assert octets.length == 4;
return octetsToString(octets) + "/" + networkMask;
}
}

View File

@ -24,7 +24,6 @@ import com.carrotsearch.hppc.ObjectLongMap;
import com.carrotsearch.hppc.cursors.ObjectCursor; import com.carrotsearch.hppc.cursors.ObjectCursor;
import com.carrotsearch.hppc.cursors.ObjectLongCursor; import com.carrotsearch.hppc.cursors.ObjectLongCursor;
import org.elasticsearch.cluster.ClusterChangedEvent; import org.elasticsearch.cluster.ClusterChangedEvent;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.RoutingNode; import org.elasticsearch.cluster.routing.RoutingNode;
import org.elasticsearch.cluster.routing.RoutingNodes; import org.elasticsearch.cluster.routing.RoutingNodes;
@ -101,7 +100,8 @@ public abstract class ReplicaShardAllocator extends AbstractComponent {
// we found a better match that has a full sync id match, the existing allocation is not fully synced // we found a better match that has a full sync id match, the existing allocation is not fully synced
// so we found a better one, cancel this one // so we found a better one, cancel this one
it.moveToUnassigned(new UnassignedInfo(UnassignedInfo.Reason.REALLOCATED_REPLICA, it.moveToUnassigned(new UnassignedInfo(UnassignedInfo.Reason.REALLOCATED_REPLICA,
"existing allocation of replica to [" + currentNode + "] cancelled, sync id match found on node [" + nodeWithHighestMatch + "]")); "existing allocation of replica to [" + currentNode + "] cancelled, sync id match found on node [" + nodeWithHighestMatch + "]",
null, allocation.getCurrentNanoTime(), System.currentTimeMillis()));
changed = true; changed = true;
} }
} }
@ -111,7 +111,6 @@ public abstract class ReplicaShardAllocator extends AbstractComponent {
} }
public boolean allocateUnassigned(RoutingAllocation allocation) { public boolean allocateUnassigned(RoutingAllocation allocation) {
long nanoTimeNow = System.nanoTime();
boolean changed = false; boolean changed = false;
final RoutingNodes routingNodes = allocation.routingNodes(); final RoutingNodes routingNodes = allocation.routingNodes();
final RoutingNodes.UnassignedShards.UnassignedIterator unassignedIterator = routingNodes.unassigned().iterator(); final RoutingNodes.UnassignedShards.UnassignedIterator unassignedIterator = routingNodes.unassigned().iterator();
@ -171,7 +170,7 @@ public abstract class ReplicaShardAllocator extends AbstractComponent {
} }
} else if (matchingNodes.hasAnyData() == false) { } else if (matchingNodes.hasAnyData() == false) {
// if we didn't manage to find *any* data (regardless of matching sizes), check if the allocation of the replica shard needs to be delayed // if we didn't manage to find *any* data (regardless of matching sizes), check if the allocation of the replica shard needs to be delayed
changed |= ignoreUnassignedIfDelayed(nanoTimeNow, allocation, unassignedIterator, shard); changed |= ignoreUnassignedIfDelayed(unassignedIterator, shard);
} }
} }
return changed; return changed;
@ -185,16 +184,13 @@ public abstract class ReplicaShardAllocator extends AbstractComponent {
* *
* PUBLIC FOR TESTS! * PUBLIC FOR TESTS!
* *
* @param timeNowNanos Timestamp in nanoseconds representing "now"
* @param allocation the routing allocation
* @param unassignedIterator iterator over unassigned shards * @param unassignedIterator iterator over unassigned shards
* @param shard the shard which might be delayed * @param shard the shard which might be delayed
* @return true iff allocation is delayed for this shard * @return true iff allocation is delayed for this shard
*/ */
public boolean ignoreUnassignedIfDelayed(long timeNowNanos, RoutingAllocation allocation, RoutingNodes.UnassignedShards.UnassignedIterator unassignedIterator, ShardRouting shard) { public boolean ignoreUnassignedIfDelayed(RoutingNodes.UnassignedShards.UnassignedIterator unassignedIterator, ShardRouting shard) {
IndexMetaData indexMetaData = allocation.metaData().index(shard.getIndex());
// calculate delay and store it in UnassignedInfo to be used by RoutingService // calculate delay and store it in UnassignedInfo to be used by RoutingService
long delay = shard.unassignedInfo().updateDelay(timeNowNanos, settings, indexMetaData.getSettings()); long delay = shard.unassignedInfo().getLastComputedLeftDelayNanos();
if (delay > 0) { if (delay > 0) {
logger.debug("[{}][{}]: delaying allocation of [{}] for [{}]", shard.index(), shard.id(), shard, TimeValue.timeValueNanos(delay)); logger.debug("[{}][{}]: delaying allocation of [{}] for [{}]", shard.index(), shard.id(), shard, TimeValue.timeValueNanos(delay));
/** /**

View File

@ -20,7 +20,6 @@
package org.elasticsearch.index; package org.elasticsearch.index;
import org.apache.lucene.util.SetOnce; import org.apache.lucene.util.SetOnce;
import org.elasticsearch.common.inject.AbstractModule;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.NodeEnvironment; import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.index.analysis.AnalysisRegistry; import org.elasticsearch.index.analysis.AnalysisRegistry;
@ -35,8 +34,8 @@ import org.elasticsearch.index.similarity.SimilarityProvider;
import org.elasticsearch.index.similarity.SimilarityService; import org.elasticsearch.index.similarity.SimilarityService;
import org.elasticsearch.index.store.IndexStore; import org.elasticsearch.index.store.IndexStore;
import org.elasticsearch.index.store.IndexStoreConfig; import org.elasticsearch.index.store.IndexStoreConfig;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.indices.cache.query.IndicesQueryCache; import org.elasticsearch.indices.cache.query.IndicesQueryCache;
import org.elasticsearch.indices.mapper.MapperRegistry;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.*;
@ -238,7 +237,7 @@ public final class IndexModule {
IndexSearcherWrapper newWrapper(final IndexService indexService); IndexSearcherWrapper newWrapper(final IndexService indexService);
} }
public IndexService newIndexService(NodeEnvironment environment, IndexService.ShardStoreDeleter shardStoreDeleter, NodeServicesProvider servicesProvider) throws IOException { public IndexService newIndexService(NodeEnvironment environment, IndexService.ShardStoreDeleter shardStoreDeleter, NodeServicesProvider servicesProvider, MapperRegistry mapperRegistry) throws IOException {
final IndexSettings settings = indexSettings.newWithListener(settingsConsumers); final IndexSettings settings = indexSettings.newWithListener(settingsConsumers);
IndexSearcherWrapperFactory searcherWrapperFactory = indexSearcherWrapper.get() == null ? (shard) -> null : indexSearcherWrapper.get(); IndexSearcherWrapperFactory searcherWrapperFactory = indexSearcherWrapper.get() == null ? (shard) -> null : indexSearcherWrapper.get();
IndexEventListener eventListener = freeze(); IndexEventListener eventListener = freeze();
@ -260,6 +259,6 @@ public final class IndexModule {
final BiFunction<IndexSettings, IndicesQueryCache, QueryCache> queryCacheProvider = queryCaches.get(queryCacheType); final BiFunction<IndexSettings, IndicesQueryCache, QueryCache> queryCacheProvider = queryCaches.get(queryCacheType);
final QueryCache queryCache = queryCacheProvider.apply(settings, servicesProvider.getIndicesQueryCache()); final QueryCache queryCache = queryCacheProvider.apply(settings, servicesProvider.getIndicesQueryCache());
return new IndexService(settings, environment, new SimilarityService(settings, similarities), shardStoreDeleter, analysisRegistry, engineFactory.get(), return new IndexService(settings, environment, new SimilarityService(settings, similarities), shardStoreDeleter, analysisRegistry, engineFactory.get(),
servicesProvider, queryCache, store, eventListener, searcherWrapperFactory); servicesProvider, queryCache, store, eventListener, searcherWrapperFactory, mapperRegistry);
} }
} }

View File

@ -54,6 +54,7 @@ import org.elasticsearch.index.store.IndexStore;
import org.elasticsearch.index.store.Store; import org.elasticsearch.index.store.Store;
import org.elasticsearch.indices.AliasFilterParsingException; import org.elasticsearch.indices.AliasFilterParsingException;
import org.elasticsearch.indices.InvalidAliasNameException; import org.elasticsearch.indices.InvalidAliasNameException;
import org.elasticsearch.indices.mapper.MapperRegistry;
import java.io.Closeable; import java.io.Closeable;
import java.io.IOException; import java.io.IOException;
@ -102,12 +103,13 @@ public final class IndexService extends AbstractIndexComponent implements IndexC
QueryCache queryCache, QueryCache queryCache,
IndexStore indexStore, IndexStore indexStore,
IndexEventListener eventListener, IndexEventListener eventListener,
IndexModule.IndexSearcherWrapperFactory wrapperFactory) throws IOException { IndexModule.IndexSearcherWrapperFactory wrapperFactory,
MapperRegistry mapperRegistry) throws IOException {
super(indexSettings); super(indexSettings);
this.indexSettings = indexSettings; this.indexSettings = indexSettings;
this.analysisService = registry.build(indexSettings); this.analysisService = registry.build(indexSettings);
this.similarityService = similarityService; this.similarityService = similarityService;
this.mapperService = new MapperService(indexSettings, analysisService, similarityService); this.mapperService = new MapperService(indexSettings, analysisService, similarityService, mapperRegistry);
this.indexFieldData = new IndexFieldDataService(indexSettings, nodeServicesProvider.getIndicesFieldDataCache(), nodeServicesProvider.getCircuitBreakerService(), mapperService); this.indexFieldData = new IndexFieldDataService(indexSettings, nodeServicesProvider.getIndicesFieldDataCache(), nodeServicesProvider.getCircuitBreakerService(), mapperService);
this.shardStoreDeleter = shardStoreDeleter; this.shardStoreDeleter = shardStoreDeleter;
this.eventListener = eventListener; this.eventListener = eventListener;
@ -216,7 +218,7 @@ public final class IndexService extends AbstractIndexComponent implements IndexC
} }
} }
public synchronized IndexShard createShard(int sShardId, ShardRouting routing) throws IOException { public synchronized IndexShard createShard(ShardRouting routing) throws IOException {
final boolean primary = routing.primary(); final boolean primary = routing.primary();
/* /*
* TODO: we execute this in parallel but it's a synced method. Yet, we might * TODO: we execute this in parallel but it's a synced method. Yet, we might
@ -224,10 +226,10 @@ public final class IndexService extends AbstractIndexComponent implements IndexC
* keep it synced. * keep it synced.
*/ */
if (closed.get()) { if (closed.get()) {
throw new IllegalStateException("Can't create shard [" + index().name() + "][" + sShardId + "], closed"); throw new IllegalStateException("Can't create shard " + routing.shardId() + ", closed");
} }
final Settings indexSettings = this.indexSettings.getSettings(); final Settings indexSettings = this.indexSettings.getSettings();
final ShardId shardId = new ShardId(index(), sShardId); final ShardId shardId = routing.shardId();
boolean success = false; boolean success = false;
Store store = null; Store store = null;
IndexShard indexShard = null; IndexShard indexShard = null;
@ -285,6 +287,7 @@ public final class IndexService extends AbstractIndexComponent implements IndexC
eventListener.indexShardStateChanged(indexShard, null, indexShard.state(), "shard created"); eventListener.indexShardStateChanged(indexShard, null, indexShard.state(), "shard created");
eventListener.afterIndexShardCreated(indexShard); eventListener.afterIndexShardCreated(indexShard);
indexShard.updateRoutingEntry(routing, true);
shards = newMapBuilder(shards).put(shardId.id(), indexShard).immutableMap(); shards = newMapBuilder(shards).put(shardId.id(), indexShard).immutableMap();
success = true; success = true;
return indexShard; return indexShard;

View File

@ -35,8 +35,8 @@ import org.elasticsearch.common.util.concurrent.ReleasableLock;
import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.mapper.MetadataFieldMapper.TypeParser;
import org.elasticsearch.index.mapper.internal.AllFieldMapper; import org.elasticsearch.index.mapper.internal.AllFieldMapper;
import org.elasticsearch.index.mapper.internal.FieldNamesFieldMapper;
import org.elasticsearch.index.mapper.internal.IdFieldMapper; import org.elasticsearch.index.mapper.internal.IdFieldMapper;
import org.elasticsearch.index.mapper.internal.IndexFieldMapper; import org.elasticsearch.index.mapper.internal.IndexFieldMapper;
import org.elasticsearch.index.mapper.internal.ParentFieldMapper; import org.elasticsearch.index.mapper.internal.ParentFieldMapper;
@ -46,14 +46,8 @@ import org.elasticsearch.index.mapper.internal.TTLFieldMapper;
import org.elasticsearch.index.mapper.internal.TimestampFieldMapper; import org.elasticsearch.index.mapper.internal.TimestampFieldMapper;
import org.elasticsearch.index.mapper.internal.TypeFieldMapper; import org.elasticsearch.index.mapper.internal.TypeFieldMapper;
import org.elasticsearch.index.mapper.internal.UidFieldMapper; import org.elasticsearch.index.mapper.internal.UidFieldMapper;
import org.elasticsearch.index.mapper.internal.VersionFieldMapper;
import org.elasticsearch.index.mapper.object.ObjectMapper; import org.elasticsearch.index.mapper.object.ObjectMapper;
import org.elasticsearch.index.mapper.object.RootObjectMapper; import org.elasticsearch.index.mapper.object.RootObjectMapper;
import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptService.ScriptType;
import org.elasticsearch.search.internal.SearchContext; import org.elasticsearch.search.internal.SearchContext;
import java.io.IOException; import java.io.IOException;
@ -76,7 +70,7 @@ public class DocumentMapper implements ToXContent {
public static class Builder { public static class Builder {
private Map<Class<? extends MetadataFieldMapper>, MetadataFieldMapper> rootMappers = new LinkedHashMap<>(); private Map<Class<? extends MetadataFieldMapper>, MetadataFieldMapper> metadataMappers = new LinkedHashMap<>();
private final Settings indexSettings; private final Settings indexSettings;
@ -91,25 +85,12 @@ public class DocumentMapper implements ToXContent {
this.builderContext = new Mapper.BuilderContext(indexSettings, new ContentPath(1)); this.builderContext = new Mapper.BuilderContext(indexSettings, new ContentPath(1));
this.rootObjectMapper = builder.build(builderContext); this.rootObjectMapper = builder.build(builderContext);
// TODO: find a cleaner way to handle existing root mappings and using their field type as the default. for (Map.Entry<String, MetadataFieldMapper.TypeParser> entry : mapperService.mapperRegistry.getMetadataMapperParsers().entrySet()) {
// the vast majority of these root mappers only need the existing type for backwards compatibility, since final String name = entry.getKey();
// the pre 2.0 field type settings could be modified final TypeParser parser = entry.getValue();
final MetadataFieldMapper metadataMapper = parser.getDefault(indexSettings, mapperService.fullName(name), builder.name());
// UID first so it will be the first stored field to load (so will benefit from "fields: []" early termination metadataMappers.put(metadataMapper.getClass(), metadataMapper);
this.rootMappers.put(UidFieldMapper.class, new UidFieldMapper(indexSettings, mapperService.fullName(UidFieldMapper.NAME))); }
this.rootMappers.put(IdFieldMapper.class, new IdFieldMapper(indexSettings, mapperService.fullName(IdFieldMapper.NAME)));
this.rootMappers.put(RoutingFieldMapper.class, new RoutingFieldMapper(indexSettings, mapperService.fullName(RoutingFieldMapper.NAME)));
// add default mappers, order is important (for example analyzer should come before the rest to set context.analyzer)
this.rootMappers.put(IndexFieldMapper.class, new IndexFieldMapper(indexSettings, mapperService.fullName(IndexFieldMapper.NAME)));
this.rootMappers.put(SourceFieldMapper.class, new SourceFieldMapper(indexSettings));
this.rootMappers.put(TypeFieldMapper.class, new TypeFieldMapper(indexSettings, mapperService.fullName(TypeFieldMapper.NAME)));
this.rootMappers.put(AllFieldMapper.class, new AllFieldMapper(indexSettings, mapperService.fullName(AllFieldMapper.NAME)));
this.rootMappers.put(TimestampFieldMapper.class, new TimestampFieldMapper(indexSettings, mapperService.fullName(TimestampFieldMapper.NAME)));
this.rootMappers.put(TTLFieldMapper.class, new TTLFieldMapper(indexSettings));
this.rootMappers.put(VersionFieldMapper.class, new VersionFieldMapper(indexSettings));
this.rootMappers.put(ParentFieldMapper.class, new ParentFieldMapper(indexSettings, mapperService.fullName(ParentFieldMapper.NAME), /* parent type */builder.name()));
// _field_names last so that it can see all other fields
this.rootMappers.put(FieldNamesFieldMapper.class, new FieldNamesFieldMapper(indexSettings, mapperService.fullName(FieldNamesFieldMapper.NAME)));
} }
public Builder meta(Map<String, Object> meta) { public Builder meta(Map<String, Object> meta) {
@ -119,13 +100,13 @@ public class DocumentMapper implements ToXContent {
public Builder put(MetadataFieldMapper.Builder<?, ?> mapper) { public Builder put(MetadataFieldMapper.Builder<?, ?> mapper) {
MetadataFieldMapper metadataMapper = mapper.build(builderContext); MetadataFieldMapper metadataMapper = mapper.build(builderContext);
rootMappers.put(metadataMapper.getClass(), metadataMapper); metadataMappers.put(metadataMapper.getClass(), metadataMapper);
return this; return this;
} }
public DocumentMapper build(MapperService mapperService, DocumentMapperParser docMapperParser) { public DocumentMapper build(MapperService mapperService, DocumentMapperParser docMapperParser) {
Objects.requireNonNull(rootObjectMapper, "Mapper builder must have the root object mapper set"); Objects.requireNonNull(rootObjectMapper, "Mapper builder must have the root object mapper set");
return new DocumentMapper(mapperService, indexSettings, docMapperParser, rootObjectMapper, meta, rootMappers, mapperService.mappingLock); return new DocumentMapper(mapperService, indexSettings, docMapperParser, rootObjectMapper, meta, metadataMappers, mapperService.mappingLock);
} }
} }
@ -152,7 +133,7 @@ public class DocumentMapper implements ToXContent {
public DocumentMapper(MapperService mapperService, @Nullable Settings indexSettings, DocumentMapperParser docMapperParser, public DocumentMapper(MapperService mapperService, @Nullable Settings indexSettings, DocumentMapperParser docMapperParser,
RootObjectMapper rootObjectMapper, RootObjectMapper rootObjectMapper,
Map<String, Object> meta, Map<String, Object> meta,
Map<Class<? extends MetadataFieldMapper>, MetadataFieldMapper> rootMappers, Map<Class<? extends MetadataFieldMapper>, MetadataFieldMapper> metadataMappers,
ReentrantReadWriteLock mappingLock) { ReentrantReadWriteLock mappingLock) {
this.mapperService = mapperService; this.mapperService = mapperService;
this.type = rootObjectMapper.name(); this.type = rootObjectMapper.name();
@ -160,16 +141,16 @@ public class DocumentMapper implements ToXContent {
this.mapping = new Mapping( this.mapping = new Mapping(
Version.indexCreated(indexSettings), Version.indexCreated(indexSettings),
rootObjectMapper, rootObjectMapper,
rootMappers.values().toArray(new MetadataFieldMapper[rootMappers.values().size()]), metadataMappers.values().toArray(new MetadataFieldMapper[metadataMappers.values().size()]),
meta); meta);
this.documentParser = new DocumentParser(indexSettings, docMapperParser, this, new ReleasableLock(mappingLock.readLock())); this.documentParser = new DocumentParser(indexSettings, docMapperParser, this, new ReleasableLock(mappingLock.readLock()));
this.mappingWriteLock = new ReleasableLock(mappingLock.writeLock()); this.mappingWriteLock = new ReleasableLock(mappingLock.writeLock());
this.mappingLock = mappingLock; this.mappingLock = mappingLock;
if (rootMapper(ParentFieldMapper.class).active()) { if (metadataMapper(ParentFieldMapper.class).active()) {
// mark the routing field mapper as required // mark the routing field mapper as required
rootMapper(RoutingFieldMapper.class).markAsRequired(); metadataMapper(RoutingFieldMapper.class).markAsRequired();
} }
// collect all the mappers for this type // collect all the mappers for this type
@ -227,52 +208,52 @@ public class DocumentMapper implements ToXContent {
} }
public UidFieldMapper uidMapper() { public UidFieldMapper uidMapper() {
return rootMapper(UidFieldMapper.class); return metadataMapper(UidFieldMapper.class);
} }
@SuppressWarnings({"unchecked"}) @SuppressWarnings({"unchecked"})
public <T extends MetadataFieldMapper> T rootMapper(Class<T> type) { public <T extends MetadataFieldMapper> T metadataMapper(Class<T> type) {
return mapping.rootMapper(type); return mapping.metadataMapper(type);
} }
public IndexFieldMapper indexMapper() { public IndexFieldMapper indexMapper() {
return rootMapper(IndexFieldMapper.class); return metadataMapper(IndexFieldMapper.class);
} }
public TypeFieldMapper typeMapper() { public TypeFieldMapper typeMapper() {
return rootMapper(TypeFieldMapper.class); return metadataMapper(TypeFieldMapper.class);
} }
public SourceFieldMapper sourceMapper() { public SourceFieldMapper sourceMapper() {
return rootMapper(SourceFieldMapper.class); return metadataMapper(SourceFieldMapper.class);
} }
public AllFieldMapper allFieldMapper() { public AllFieldMapper allFieldMapper() {
return rootMapper(AllFieldMapper.class); return metadataMapper(AllFieldMapper.class);
} }
public IdFieldMapper idFieldMapper() { public IdFieldMapper idFieldMapper() {
return rootMapper(IdFieldMapper.class); return metadataMapper(IdFieldMapper.class);
} }
public RoutingFieldMapper routingFieldMapper() { public RoutingFieldMapper routingFieldMapper() {
return rootMapper(RoutingFieldMapper.class); return metadataMapper(RoutingFieldMapper.class);
} }
public ParentFieldMapper parentFieldMapper() { public ParentFieldMapper parentFieldMapper() {
return rootMapper(ParentFieldMapper.class); return metadataMapper(ParentFieldMapper.class);
} }
public TimestampFieldMapper timestampFieldMapper() { public TimestampFieldMapper timestampFieldMapper() {
return rootMapper(TimestampFieldMapper.class); return metadataMapper(TimestampFieldMapper.class);
} }
public TTLFieldMapper TTLFieldMapper() { public TTLFieldMapper TTLFieldMapper() {
return rootMapper(TTLFieldMapper.class); return metadataMapper(TTLFieldMapper.class);
} }
public IndexFieldMapper IndexFieldMapper() { public IndexFieldMapper IndexFieldMapper() {
return rootMapper(IndexFieldMapper.class); return metadataMapper(IndexFieldMapper.class);
} }
public Query typeFilter() { public Query typeFilter() {

View File

@ -25,7 +25,6 @@ import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.compress.CompressedXContent; import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.geo.ShapesAvailability;
import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
@ -34,19 +33,13 @@ import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.analysis.AnalysisService; import org.elasticsearch.index.analysis.AnalysisService;
import org.elasticsearch.index.mapper.core.*;
import org.elasticsearch.index.mapper.geo.GeoPointFieldMapper;
import org.elasticsearch.index.mapper.geo.GeoShapeFieldMapper;
import org.elasticsearch.index.mapper.internal.*;
import org.elasticsearch.index.mapper.ip.IpFieldMapper;
import org.elasticsearch.index.mapper.object.ObjectMapper;
import org.elasticsearch.index.mapper.object.RootObjectMapper; import org.elasticsearch.index.mapper.object.RootObjectMapper;
import org.elasticsearch.index.similarity.SimilarityService; import org.elasticsearch.index.similarity.SimilarityService;
import org.elasticsearch.indices.mapper.MapperRegistry;
import java.util.*; import java.util.*;
import static java.util.Collections.unmodifiableMap; import static java.util.Collections.unmodifiableMap;
import static java.util.Collections.unmodifiableSortedMap;
import static org.elasticsearch.index.mapper.MapperBuilders.doc; import static org.elasticsearch.index.mapper.MapperBuilders.doc;
public class DocumentMapperParser { public class DocumentMapperParser {
@ -59,83 +52,24 @@ public class DocumentMapperParser {
private final RootObjectMapper.TypeParser rootObjectTypeParser = new RootObjectMapper.TypeParser(); private final RootObjectMapper.TypeParser rootObjectTypeParser = new RootObjectMapper.TypeParser();
private final Object typeParsersMutex = new Object();
private final Version indexVersionCreated; private final Version indexVersionCreated;
private final ParseFieldMatcher parseFieldMatcher; private final ParseFieldMatcher parseFieldMatcher;
private volatile Map<String, Mapper.TypeParser> typeParsers; private final Map<String, Mapper.TypeParser> typeParsers;
private volatile Map<String, Mapper.TypeParser> rootTypeParsers; private final Map<String, MetadataFieldMapper.TypeParser> rootTypeParsers;
private volatile SortedMap<String, Mapper.TypeParser> additionalRootMappers;
public DocumentMapperParser(IndexSettings indexSettings, MapperService mapperService, AnalysisService analysisService, public DocumentMapperParser(IndexSettings indexSettings, MapperService mapperService, AnalysisService analysisService,
SimilarityService similarityService) { SimilarityService similarityService, MapperRegistry mapperRegistry) {
this.indexSettings = indexSettings.getSettings(); this.indexSettings = indexSettings.getSettings();
this.parseFieldMatcher = new ParseFieldMatcher(this.indexSettings); this.parseFieldMatcher = new ParseFieldMatcher(this.indexSettings);
this.mapperService = mapperService; this.mapperService = mapperService;
this.analysisService = analysisService; this.analysisService = analysisService;
this.similarityService = similarityService; this.similarityService = similarityService;
Map<String, Mapper.TypeParser> typeParsers = new HashMap<>(); this.typeParsers = mapperRegistry.getMapperParsers();
typeParsers.put(ByteFieldMapper.CONTENT_TYPE, new ByteFieldMapper.TypeParser()); this.rootTypeParsers = mapperRegistry.getMetadataMapperParsers();
typeParsers.put(ShortFieldMapper.CONTENT_TYPE, new ShortFieldMapper.TypeParser());
typeParsers.put(IntegerFieldMapper.CONTENT_TYPE, new IntegerFieldMapper.TypeParser());
typeParsers.put(LongFieldMapper.CONTENT_TYPE, new LongFieldMapper.TypeParser());
typeParsers.put(FloatFieldMapper.CONTENT_TYPE, new FloatFieldMapper.TypeParser());
typeParsers.put(DoubleFieldMapper.CONTENT_TYPE, new DoubleFieldMapper.TypeParser());
typeParsers.put(BooleanFieldMapper.CONTENT_TYPE, new BooleanFieldMapper.TypeParser());
typeParsers.put(BinaryFieldMapper.CONTENT_TYPE, new BinaryFieldMapper.TypeParser());
typeParsers.put(DateFieldMapper.CONTENT_TYPE, new DateFieldMapper.TypeParser());
typeParsers.put(IpFieldMapper.CONTENT_TYPE, new IpFieldMapper.TypeParser());
typeParsers.put(StringFieldMapper.CONTENT_TYPE, new StringFieldMapper.TypeParser());
typeParsers.put(TokenCountFieldMapper.CONTENT_TYPE, new TokenCountFieldMapper.TypeParser());
typeParsers.put(ObjectMapper.CONTENT_TYPE, new ObjectMapper.TypeParser());
typeParsers.put(ObjectMapper.NESTED_CONTENT_TYPE, new ObjectMapper.TypeParser());
typeParsers.put(TypeParsers.MULTI_FIELD_CONTENT_TYPE, TypeParsers.multiFieldConverterTypeParser);
typeParsers.put(CompletionFieldMapper.CONTENT_TYPE, new CompletionFieldMapper.TypeParser());
typeParsers.put(GeoPointFieldMapper.CONTENT_TYPE, new GeoPointFieldMapper.TypeParser());
if (ShapesAvailability.JTS_AVAILABLE) {
typeParsers.put(GeoShapeFieldMapper.CONTENT_TYPE, new GeoShapeFieldMapper.TypeParser());
}
this.typeParsers = unmodifiableMap(typeParsers);
Map<String, Mapper.TypeParser> rootTypeParsers = new HashMap<>();
rootTypeParsers.put(IndexFieldMapper.NAME, new IndexFieldMapper.TypeParser());
rootTypeParsers.put(SourceFieldMapper.NAME, new SourceFieldMapper.TypeParser());
rootTypeParsers.put(TypeFieldMapper.NAME, new TypeFieldMapper.TypeParser());
rootTypeParsers.put(AllFieldMapper.NAME, new AllFieldMapper.TypeParser());
rootTypeParsers.put(ParentFieldMapper.NAME, new ParentFieldMapper.TypeParser());
rootTypeParsers.put(RoutingFieldMapper.NAME, new RoutingFieldMapper.TypeParser());
rootTypeParsers.put(TimestampFieldMapper.NAME, new TimestampFieldMapper.TypeParser());
rootTypeParsers.put(TTLFieldMapper.NAME, new TTLFieldMapper.TypeParser());
rootTypeParsers.put(UidFieldMapper.NAME, new UidFieldMapper.TypeParser());
rootTypeParsers.put(VersionFieldMapper.NAME, new VersionFieldMapper.TypeParser());
rootTypeParsers.put(IdFieldMapper.NAME, new IdFieldMapper.TypeParser());
rootTypeParsers.put(FieldNamesFieldMapper.NAME, new FieldNamesFieldMapper.TypeParser());
this.rootTypeParsers = unmodifiableMap(rootTypeParsers);
additionalRootMappers = Collections.emptySortedMap();
indexVersionCreated = indexSettings.getIndexVersionCreated(); indexVersionCreated = indexSettings.getIndexVersionCreated();
} }
public void putTypeParser(String type, Mapper.TypeParser typeParser) {
synchronized (typeParsersMutex) {
Map<String, Mapper.TypeParser> typeParsers = new HashMap<>(this.typeParsers);
typeParsers.put(type, typeParser);
this.typeParsers = unmodifiableMap(typeParsers);
}
}
public void putRootTypeParser(String type, Mapper.TypeParser typeParser) {
synchronized (typeParsersMutex) {
Map<String, Mapper.TypeParser> rootTypeParsers = new HashMap<>(this.rootTypeParsers);
rootTypeParsers.put(type, typeParser);
this.rootTypeParsers = rootTypeParsers;
SortedMap<String, Mapper.TypeParser> additionalRootMappers = new TreeMap<>(this.additionalRootMappers);
additionalRootMappers.put(type, typeParser);
this.additionalRootMappers = unmodifiableSortedMap(additionalRootMappers);
}
}
public Mapper.TypeParser.ParserContext parserContext(String type) { public Mapper.TypeParser.ParserContext parserContext(String type) {
return new Mapper.TypeParser.ParserContext(type, analysisService, similarityService::getSimilarity, mapperService, typeParsers::get, indexVersionCreated, parseFieldMatcher); return new Mapper.TypeParser.ParserContext(type, analysisService, similarityService::getSimilarity, mapperService, typeParsers::get, indexVersionCreated, parseFieldMatcher);
} }
@ -148,7 +82,6 @@ public class DocumentMapperParser {
return parse(type, source, null); return parse(type, source, null);
} }
@SuppressWarnings({"unchecked"})
public DocumentMapper parse(@Nullable String type, String source, String defaultSource) throws MapperParsingException { public DocumentMapper parse(@Nullable String type, String source, String defaultSource) throws MapperParsingException {
Map<String, Object> mapping = null; Map<String, Object> mapping = null;
if (source != null) { if (source != null) {
@ -166,7 +99,6 @@ public class DocumentMapperParser {
return parseCompressed(type, source, null); return parseCompressed(type, source, null);
} }
@SuppressWarnings({"unchecked"})
public DocumentMapper parseCompressed(@Nullable String type, CompressedXContent source, String defaultSource) throws MapperParsingException { public DocumentMapper parseCompressed(@Nullable String type, CompressedXContent source, String defaultSource) throws MapperParsingException {
Map<String, Object> mapping = null; Map<String, Object> mapping = null;
if (source != null) { if (source != null) {
@ -198,10 +130,6 @@ public class DocumentMapperParser {
Mapper.TypeParser.ParserContext parserContext = parserContext(type); Mapper.TypeParser.ParserContext parserContext = parserContext(type);
// parse RootObjectMapper // parse RootObjectMapper
DocumentMapper.Builder docBuilder = doc(indexSettings, (RootObjectMapper.Builder) rootObjectTypeParser.parse(type, mapping, parserContext), mapperService); DocumentMapper.Builder docBuilder = doc(indexSettings, (RootObjectMapper.Builder) rootObjectTypeParser.parse(type, mapping, parserContext), mapperService);
// Add default mapping for the plugged-in meta mappers
for (Map.Entry<String, Mapper.TypeParser> entry : additionalRootMappers.entrySet()) {
docBuilder.put((MetadataFieldMapper.Builder<?, ?>) entry.getValue().parse(entry.getKey(), Collections.<String, Object>emptyMap(), parserContext));
}
Iterator<Map.Entry<String, Object>> iterator = mapping.entrySet().iterator(); Iterator<Map.Entry<String, Object>> iterator = mapping.entrySet().iterator();
// parse DocumentMapper // parse DocumentMapper
while(iterator.hasNext()) { while(iterator.hasNext()) {
@ -209,11 +137,11 @@ public class DocumentMapperParser {
String fieldName = Strings.toUnderscoreCase(entry.getKey()); String fieldName = Strings.toUnderscoreCase(entry.getKey());
Object fieldNode = entry.getValue(); Object fieldNode = entry.getValue();
Mapper.TypeParser typeParser = rootTypeParsers.get(fieldName); MetadataFieldMapper.TypeParser typeParser = rootTypeParsers.get(fieldName);
if (typeParser != null) { if (typeParser != null) {
iterator.remove(); iterator.remove();
Map<String, Object> fieldNodeMap = (Map<String, Object>) fieldNode; Map<String, Object> fieldNodeMap = (Map<String, Object>) fieldNode;
docBuilder.put((MetadataFieldMapper.Builder) typeParser.parse(fieldName, fieldNodeMap, parserContext)); docBuilder.put(typeParser.parse(fieldName, fieldNodeMap, parserContext));
fieldNodeMap.remove("type"); fieldNodeMap.remove("type");
checkNoRemainingFields(fieldName, fieldNodeMap, parserContext.indexVersionCreated()); checkNoRemainingFields(fieldName, fieldNodeMap, parserContext.indexVersionCreated());
} }

View File

@ -20,6 +20,7 @@
package org.elasticsearch.index.mapper; package org.elasticsearch.index.mapper;
import com.carrotsearch.hppc.ObjectHashSet; import com.carrotsearch.hppc.ObjectHashSet;
import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.DelegatingAnalyzerWrapper; import org.apache.lucene.analysis.DelegatingAnalyzerWrapper;
import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.IndexOptions;
@ -45,6 +46,7 @@ import org.elasticsearch.index.mapper.object.ObjectMapper;
import org.elasticsearch.index.similarity.SimilarityService; import org.elasticsearch.index.similarity.SimilarityService;
import org.elasticsearch.indices.InvalidTypeNameException; import org.elasticsearch.indices.InvalidTypeNameException;
import org.elasticsearch.indices.TypeMissingException; import org.elasticsearch.indices.TypeMissingException;
import org.elasticsearch.indices.mapper.MapperRegistry;
import org.elasticsearch.percolator.PercolatorService; import org.elasticsearch.percolator.PercolatorService;
import org.elasticsearch.script.ScriptService; import org.elasticsearch.script.ScriptService;
@ -104,15 +106,18 @@ public class MapperService extends AbstractIndexComponent implements Closeable {
private volatile Set<String> parentTypes = emptySet(); private volatile Set<String> parentTypes = emptySet();
final MapperRegistry mapperRegistry;
public MapperService(IndexSettings indexSettings, AnalysisService analysisService, public MapperService(IndexSettings indexSettings, AnalysisService analysisService,
SimilarityService similarityService) { SimilarityService similarityService, MapperRegistry mapperRegistry) {
super(indexSettings); super(indexSettings);
this.analysisService = analysisService; this.analysisService = analysisService;
this.fieldTypes = new FieldTypeLookup(); this.fieldTypes = new FieldTypeLookup();
this.documentParser = new DocumentMapperParser(indexSettings, this, analysisService, similarityService); this.documentParser = new DocumentMapperParser(indexSettings, this, analysisService, similarityService, mapperRegistry);
this.indexAnalyzer = new MapperAnalyzerWrapper(analysisService.defaultIndexAnalyzer(), p -> p.indexAnalyzer()); this.indexAnalyzer = new MapperAnalyzerWrapper(analysisService.defaultIndexAnalyzer(), p -> p.indexAnalyzer());
this.searchAnalyzer = new MapperAnalyzerWrapper(analysisService.defaultSearchAnalyzer(), p -> p.searchAnalyzer()); this.searchAnalyzer = new MapperAnalyzerWrapper(analysisService.defaultSearchAnalyzer(), p -> p.searchAnalyzer());
this.searchQuoteAnalyzer = new MapperAnalyzerWrapper(analysisService.defaultSearchQuoteAnalyzer(), p -> p.searchQuoteAnalyzer()); this.searchQuoteAnalyzer = new MapperAnalyzerWrapper(analysisService.defaultSearchQuoteAnalyzer(), p -> p.searchQuoteAnalyzer());
this.mapperRegistry = mapperRegistry;
this.dynamic = this.indexSettings.getSettings().getAsBoolean("index.mapper.dynamic", true); this.dynamic = this.indexSettings.getSettings().getAsBoolean("index.mapper.dynamic", true);
defaultPercolatorMappingSource = "{\n" + defaultPercolatorMappingSource = "{\n" +

View File

@ -46,19 +46,19 @@ public final class Mapping implements ToXContent {
final Version indexCreated; final Version indexCreated;
final RootObjectMapper root; final RootObjectMapper root;
final MetadataFieldMapper[] metadataMappers; final MetadataFieldMapper[] metadataMappers;
final Map<Class<? extends MetadataFieldMapper>, MetadataFieldMapper> rootMappersMap; final Map<Class<? extends MetadataFieldMapper>, MetadataFieldMapper> metadataMappersMap;
volatile Map<String, Object> meta; volatile Map<String, Object> meta;
public Mapping(Version indexCreated, RootObjectMapper rootObjectMapper, MetadataFieldMapper[] metadataMappers, Map<String, Object> meta) { public Mapping(Version indexCreated, RootObjectMapper rootObjectMapper, MetadataFieldMapper[] metadataMappers, Map<String, Object> meta) {
this.indexCreated = indexCreated; this.indexCreated = indexCreated;
this.root = rootObjectMapper; this.root = rootObjectMapper;
this.metadataMappers = metadataMappers; this.metadataMappers = metadataMappers;
Map<Class<? extends MetadataFieldMapper>, MetadataFieldMapper> rootMappersMap = new HashMap<>(); Map<Class<? extends MetadataFieldMapper>, MetadataFieldMapper> metadataMappersMap = new HashMap<>();
for (MetadataFieldMapper metadataMapper : metadataMappers) { for (MetadataFieldMapper metadataMapper : metadataMappers) {
if (indexCreated.before(Version.V_2_0_0_beta1) && LEGACY_INCLUDE_IN_OBJECT.contains(metadataMapper.name())) { if (indexCreated.before(Version.V_2_0_0_beta1) && LEGACY_INCLUDE_IN_OBJECT.contains(metadataMapper.name())) {
root.putMapper(metadataMapper); root.putMapper(metadataMapper);
} }
rootMappersMap.put(metadataMapper.getClass(), metadataMapper); metadataMappersMap.put(metadataMapper.getClass(), metadataMapper);
} }
// keep root mappers sorted for consistent serialization // keep root mappers sorted for consistent serialization
Arrays.sort(metadataMappers, new Comparator<Mapper>() { Arrays.sort(metadataMappers, new Comparator<Mapper>() {
@ -67,7 +67,7 @@ public final class Mapping implements ToXContent {
return o1.name().compareTo(o2.name()); return o1.name().compareTo(o2.name());
} }
}); });
this.rootMappersMap = unmodifiableMap(rootMappersMap); this.metadataMappersMap = unmodifiableMap(metadataMappersMap);
this.meta = meta; this.meta = meta;
} }
@ -85,8 +85,8 @@ public final class Mapping implements ToXContent {
/** Get the root mapper with the given class. */ /** Get the root mapper with the given class. */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T extends MetadataFieldMapper> T rootMapper(Class<T> clazz) { public <T extends MetadataFieldMapper> T metadataMapper(Class<T> clazz) {
return (T) rootMappersMap.get(clazz); return (T) metadataMappersMap.get(clazz);
} }
/** @see DocumentMapper#merge(Mapping, boolean, boolean) */ /** @see DocumentMapper#merge(Mapping, boolean, boolean) */
@ -95,7 +95,7 @@ public final class Mapping implements ToXContent {
root.merge(mergeWith.root, mergeResult); root.merge(mergeWith.root, mergeResult);
for (MetadataFieldMapper metadataMapper : metadataMappers) { for (MetadataFieldMapper metadataMapper : metadataMappers) {
MetadataFieldMapper mergeWithMetadataMapper = mergeWith.rootMapper(metadataMapper.getClass()); MetadataFieldMapper mergeWithMetadataMapper = mergeWith.metadataMapper(metadataMapper.getClass());
if (mergeWithMetadataMapper != null) { if (mergeWithMetadataMapper != null) {
metadataMapper.merge(mergeWithMetadataMapper, mergeResult); metadataMapper.merge(mergeWithMetadataMapper, mergeResult);
} }

View File

@ -23,6 +23,7 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.mapper.object.RootObjectMapper; import org.elasticsearch.index.mapper.object.RootObjectMapper;
import java.io.IOException; import java.io.IOException;
import java.util.Map;
/** /**
@ -30,6 +31,25 @@ import java.io.IOException;
*/ */
public abstract class MetadataFieldMapper extends FieldMapper { public abstract class MetadataFieldMapper extends FieldMapper {
public static interface TypeParser extends Mapper.TypeParser {
@Override
MetadataFieldMapper.Builder<?,?> parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException;
/**
* Get the default {@link MetadataFieldMapper} to use, if nothing had to be parsed.
* @param fieldType null if this is the first root mapper on this index, the existing
* fieldType for this index otherwise
* @param indexSettings the index-level settings
* @param fieldType the existing field type for this meta mapper on the current index
* or null if this is the first type being introduced
* @param typeName the name of the type that this mapper will be used on
*/
// TODO: remove the fieldType parameter which is only used for bw compat with pre-2.0
// since settings could be modified
MetadataFieldMapper getDefault(Settings indexSettings, MappedFieldType fieldType, String typeName);
}
public abstract static class Builder<T extends Builder, Y extends MetadataFieldMapper> extends FieldMapper.Builder<T, Y> { public abstract static class Builder<T extends Builder, Y extends MetadataFieldMapper> extends FieldMapper.Builder<T, Y> {
public Builder(String name, MappedFieldType fieldType) { public Builder(String name, MappedFieldType fieldType) {
super(name, fieldType); super(name, fieldType);

View File

@ -113,9 +113,9 @@ public class AllFieldMapper extends MetadataFieldMapper {
} }
} }
public static class TypeParser implements Mapper.TypeParser { public static class TypeParser implements MetadataFieldMapper.TypeParser {
@Override @Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { public MetadataFieldMapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
Builder builder = new Builder(parserContext.mapperService().fullName(NAME)); Builder builder = new Builder(parserContext.mapperService().fullName(NAME));
// parseField below will happily parse the doc_values setting, but it is then never passed to // parseField below will happily parse the doc_values setting, but it is then never passed to
@ -150,6 +150,11 @@ public class AllFieldMapper extends MetadataFieldMapper {
} }
return builder; return builder;
} }
@Override
public MetadataFieldMapper getDefault(Settings indexSettings, MappedFieldType fieldType, String typeName) {
return new AllFieldMapper(indexSettings, fieldType);
}
} }
static final class AllFieldType extends MappedFieldType { static final class AllFieldType extends MappedFieldType {
@ -193,11 +198,11 @@ public class AllFieldMapper extends MetadataFieldMapper {
private EnabledAttributeMapper enabledState; private EnabledAttributeMapper enabledState;
public AllFieldMapper(Settings indexSettings, MappedFieldType existing) { private AllFieldMapper(Settings indexSettings, MappedFieldType existing) {
this(existing == null ? Defaults.FIELD_TYPE.clone() : existing.clone(), Defaults.ENABLED, indexSettings); this(existing == null ? Defaults.FIELD_TYPE.clone() : existing.clone(), Defaults.ENABLED, indexSettings);
} }
protected AllFieldMapper(MappedFieldType fieldType, EnabledAttributeMapper enabled, Settings indexSettings) { private AllFieldMapper(MappedFieldType fieldType, EnabledAttributeMapper enabled, Settings indexSettings) {
super(NAME, fieldType, Defaults.FIELD_TYPE, indexSettings); super(NAME, fieldType, Defaults.FIELD_TYPE, indexSettings);
this.enabledState = enabled; this.enabledState = enabled;

View File

@ -104,9 +104,9 @@ public class FieldNamesFieldMapper extends MetadataFieldMapper {
} }
} }
public static class TypeParser implements Mapper.TypeParser { public static class TypeParser implements MetadataFieldMapper.TypeParser {
@Override @Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { public MetadataFieldMapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
if (parserContext.indexVersionCreated().before(Version.V_1_3_0)) { if (parserContext.indexVersionCreated().before(Version.V_1_3_0)) {
throw new IllegalArgumentException("type="+CONTENT_TYPE+" is not supported on indices created before version 1.3.0. Is your cluster running multiple datanode versions?"); throw new IllegalArgumentException("type="+CONTENT_TYPE+" is not supported on indices created before version 1.3.0. Is your cluster running multiple datanode versions?");
} }
@ -127,6 +127,11 @@ public class FieldNamesFieldMapper extends MetadataFieldMapper {
} }
return builder; return builder;
} }
@Override
public MetadataFieldMapper getDefault(Settings indexSettings, MappedFieldType fieldType, String typeName) {
return new FieldNamesFieldMapper(indexSettings, fieldType);
}
} }
public static final class FieldNamesFieldType extends MappedFieldType { public static final class FieldNamesFieldType extends MappedFieldType {
@ -200,11 +205,11 @@ public class FieldNamesFieldMapper extends MetadataFieldMapper {
private final boolean pre13Index; // if the index was created before 1.3, _field_names is always disabled private final boolean pre13Index; // if the index was created before 1.3, _field_names is always disabled
public FieldNamesFieldMapper(Settings indexSettings, MappedFieldType existing) { private FieldNamesFieldMapper(Settings indexSettings, MappedFieldType existing) {
this(existing == null ? Defaults.FIELD_TYPE.clone() : existing.clone(), indexSettings); this(existing == null ? Defaults.FIELD_TYPE.clone() : existing.clone(), indexSettings);
} }
public FieldNamesFieldMapper(MappedFieldType fieldType, Settings indexSettings) { private FieldNamesFieldMapper(MappedFieldType fieldType, Settings indexSettings) {
super(NAME, fieldType, Defaults.FIELD_TYPE, indexSettings); super(NAME, fieldType, Defaults.FIELD_TYPE, indexSettings);
this.pre13Index = Version.indexCreated(indexSettings).before(Version.V_1_3_0); this.pre13Index = Version.indexCreated(indexSettings).before(Version.V_1_3_0);
if (this.pre13Index) { if (this.pre13Index) {

View File

@ -112,9 +112,9 @@ public class IdFieldMapper extends MetadataFieldMapper {
} }
} }
public static class TypeParser implements Mapper.TypeParser { public static class TypeParser implements MetadataFieldMapper.TypeParser {
@Override @Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { public MetadataFieldMapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
if (parserContext.indexVersionCreated().onOrAfter(Version.V_2_0_0_beta1)) { if (parserContext.indexVersionCreated().onOrAfter(Version.V_2_0_0_beta1)) {
throw new MapperParsingException(NAME + " is not configurable"); throw new MapperParsingException(NAME + " is not configurable");
} }
@ -131,6 +131,11 @@ public class IdFieldMapper extends MetadataFieldMapper {
} }
return builder; return builder;
} }
@Override
public MetadataFieldMapper getDefault(Settings indexSettings, MappedFieldType fieldType, String typeName) {
return new IdFieldMapper(indexSettings, fieldType);
}
} }
static final class IdFieldType extends MappedFieldType { static final class IdFieldType extends MappedFieldType {
@ -228,11 +233,11 @@ public class IdFieldMapper extends MetadataFieldMapper {
private final String path; private final String path;
public IdFieldMapper(Settings indexSettings, MappedFieldType existing) { private IdFieldMapper(Settings indexSettings, MappedFieldType existing) {
this(idFieldType(indexSettings, existing), Defaults.PATH, indexSettings); this(idFieldType(indexSettings, existing), Defaults.PATH, indexSettings);
} }
protected IdFieldMapper(MappedFieldType fieldType, String path, Settings indexSettings) { private IdFieldMapper(MappedFieldType fieldType, String path, Settings indexSettings) {
super(NAME, fieldType, Defaults.FIELD_TYPE, indexSettings); super(NAME, fieldType, Defaults.FIELD_TYPE, indexSettings);
this.path = path; this.path = path;
} }

View File

@ -98,9 +98,9 @@ public class IndexFieldMapper extends MetadataFieldMapper {
} }
} }
public static class TypeParser implements Mapper.TypeParser { public static class TypeParser implements MetadataFieldMapper.TypeParser {
@Override @Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { public MetadataFieldMapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
Builder builder = new Builder(parserContext.mapperService().fullName(NAME)); Builder builder = new Builder(parserContext.mapperService().fullName(NAME));
if (parserContext.indexVersionCreated().onOrAfter(Version.V_2_0_0_beta1)) { if (parserContext.indexVersionCreated().onOrAfter(Version.V_2_0_0_beta1)) {
return builder; return builder;
@ -119,6 +119,11 @@ public class IndexFieldMapper extends MetadataFieldMapper {
} }
return builder; return builder;
} }
@Override
public MetadataFieldMapper getDefault(Settings indexSettings, MappedFieldType fieldType, String typeName) {
return new IndexFieldMapper(indexSettings, fieldType);
}
} }
static final class IndexFieldType extends MappedFieldType { static final class IndexFieldType extends MappedFieldType {
@ -206,11 +211,11 @@ public class IndexFieldMapper extends MetadataFieldMapper {
private EnabledAttributeMapper enabledState; private EnabledAttributeMapper enabledState;
public IndexFieldMapper(Settings indexSettings, MappedFieldType existing) { private IndexFieldMapper(Settings indexSettings, MappedFieldType existing) {
this(existing == null ? Defaults.FIELD_TYPE.clone() : existing, Defaults.ENABLED_STATE, indexSettings); this(existing == null ? Defaults.FIELD_TYPE.clone() : existing, Defaults.ENABLED_STATE, indexSettings);
} }
public IndexFieldMapper(MappedFieldType fieldType, EnabledAttributeMapper enabledState, Settings indexSettings) { private IndexFieldMapper(MappedFieldType fieldType, EnabledAttributeMapper enabledState, Settings indexSettings) {
super(NAME, fieldType, Defaults.FIELD_TYPE, indexSettings); super(NAME, fieldType, Defaults.FIELD_TYPE, indexSettings);
this.enabledState = enabledState; this.enabledState = enabledState;
} }

View File

@ -129,9 +129,9 @@ public class ParentFieldMapper extends MetadataFieldMapper {
} }
} }
public static class TypeParser implements Mapper.TypeParser { public static class TypeParser implements MetadataFieldMapper.TypeParser {
@Override @Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { public MetadataFieldMapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
Builder builder = new Builder(parserContext.type()); Builder builder = new Builder(parserContext.type());
for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) { for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<String, Object> entry = iterator.next(); Map.Entry<String, Object> entry = iterator.next();
@ -155,6 +155,11 @@ public class ParentFieldMapper extends MetadataFieldMapper {
} }
return builder; return builder;
} }
@Override
public MetadataFieldMapper getDefault(Settings indexSettings, MappedFieldType fieldType, String parentType) {
return new ParentFieldMapper(indexSettings, fieldType, parentType);
}
} }
static final class ParentFieldType extends MappedFieldType { static final class ParentFieldType extends MappedFieldType {
@ -249,7 +254,7 @@ public class ParentFieldMapper extends MetadataFieldMapper {
// has no impact of field data settings, is just here for creating a join field, the parent field mapper in the child type pointing to this type determines the field data settings for this join field // has no impact of field data settings, is just here for creating a join field, the parent field mapper in the child type pointing to this type determines the field data settings for this join field
private final MappedFieldType parentJoinFieldType; private final MappedFieldType parentJoinFieldType;
protected ParentFieldMapper(MappedFieldType fieldType, MappedFieldType parentJoinFieldType, MappedFieldType childJoinFieldType, String parentType, Settings indexSettings) { private ParentFieldMapper(MappedFieldType fieldType, MappedFieldType parentJoinFieldType, MappedFieldType childJoinFieldType, String parentType, Settings indexSettings) {
super(NAME, fieldType, Defaults.FIELD_TYPE, indexSettings); super(NAME, fieldType, Defaults.FIELD_TYPE, indexSettings);
this.parentType = parentType; this.parentType = parentType;
this.parentJoinFieldType = parentJoinFieldType; this.parentJoinFieldType = parentJoinFieldType;
@ -260,7 +265,7 @@ public class ParentFieldMapper extends MetadataFieldMapper {
} }
} }
public ParentFieldMapper(Settings indexSettings, MappedFieldType existing, String parentType) { private ParentFieldMapper(Settings indexSettings, MappedFieldType existing, String parentType) {
this(existing == null ? Defaults.FIELD_TYPE.clone() : existing.clone(), joinFieldTypeForParentType(parentType, indexSettings), null, null, indexSettings); this(existing == null ? Defaults.FIELD_TYPE.clone() : existing.clone(), joinFieldTypeForParentType(parentType, indexSettings), null, null, indexSettings);
} }

View File

@ -98,9 +98,9 @@ public class RoutingFieldMapper extends MetadataFieldMapper {
} }
} }
public static class TypeParser implements Mapper.TypeParser { public static class TypeParser implements MetadataFieldMapper.TypeParser {
@Override @Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { public MetadataFieldMapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
Builder builder = new Builder(parserContext.mapperService().fullName(NAME)); Builder builder = new Builder(parserContext.mapperService().fullName(NAME));
if (parserContext.indexVersionCreated().before(Version.V_2_0_0_beta1)) { if (parserContext.indexVersionCreated().before(Version.V_2_0_0_beta1)) {
parseField(builder, builder.name, node, parserContext); parseField(builder, builder.name, node, parserContext);
@ -119,6 +119,11 @@ public class RoutingFieldMapper extends MetadataFieldMapper {
} }
return builder; return builder;
} }
@Override
public MetadataFieldMapper getDefault(Settings indexSettings, MappedFieldType fieldType, String typeName) {
return new RoutingFieldMapper(indexSettings, fieldType);
}
} }
static final class RoutingFieldType extends MappedFieldType { static final class RoutingFieldType extends MappedFieldType {
@ -153,11 +158,11 @@ public class RoutingFieldMapper extends MetadataFieldMapper {
private boolean required; private boolean required;
private final String path; private final String path;
public RoutingFieldMapper(Settings indexSettings, MappedFieldType existing) { private RoutingFieldMapper(Settings indexSettings, MappedFieldType existing) {
this(existing == null ? Defaults.FIELD_TYPE.clone() : existing.clone(), Defaults.REQUIRED, Defaults.PATH, indexSettings); this(existing == null ? Defaults.FIELD_TYPE.clone() : existing.clone(), Defaults.REQUIRED, Defaults.PATH, indexSettings);
} }
protected RoutingFieldMapper(MappedFieldType fieldType, boolean required, String path, Settings indexSettings) { private RoutingFieldMapper(MappedFieldType fieldType, boolean required, String path, Settings indexSettings) {
super(NAME, fieldType, Defaults.FIELD_TYPE, indexSettings); super(NAME, fieldType, Defaults.FIELD_TYPE, indexSettings);
this.required = required; this.required = required;
this.path = path; this.path = path;

View File

@ -143,9 +143,9 @@ public class SourceFieldMapper extends MetadataFieldMapper {
} }
} }
public static class TypeParser implements Mapper.TypeParser { public static class TypeParser implements MetadataFieldMapper.TypeParser {
@Override @Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { public MetadataFieldMapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
Builder builder = new Builder(); Builder builder = new Builder();
for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) { for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) {
@ -194,6 +194,11 @@ public class SourceFieldMapper extends MetadataFieldMapper {
} }
return builder; return builder;
} }
@Override
public MetadataFieldMapper getDefault(Settings indexSettings, MappedFieldType fieldType, String typeName) {
return new SourceFieldMapper(indexSettings);
}
} }
static final class SourceFieldType extends MappedFieldType { static final class SourceFieldType extends MappedFieldType {
@ -248,11 +253,11 @@ public class SourceFieldMapper extends MetadataFieldMapper {
private XContentType formatContentType; private XContentType formatContentType;
public SourceFieldMapper(Settings indexSettings) { private SourceFieldMapper(Settings indexSettings) {
this(Defaults.ENABLED, Defaults.FORMAT, null, -1, null, null, indexSettings); this(Defaults.ENABLED, Defaults.FORMAT, null, -1, null, null, indexSettings);
} }
protected SourceFieldMapper(boolean enabled, String format, Boolean compress, long compressThreshold, private SourceFieldMapper(boolean enabled, String format, Boolean compress, long compressThreshold,
String[] includes, String[] excludes, Settings indexSettings) { String[] includes, String[] excludes, Settings indexSettings) {
super(NAME, Defaults.FIELD_TYPE.clone(), Defaults.FIELD_TYPE, indexSettings); // Only stored. super(NAME, Defaults.FIELD_TYPE.clone(), Defaults.FIELD_TYPE, indexSettings); // Only stored.
this.enabled = enabled; this.enabled = enabled;

View File

@ -101,9 +101,9 @@ public class TTLFieldMapper extends MetadataFieldMapper {
} }
} }
public static class TypeParser implements Mapper.TypeParser { public static class TypeParser implements MetadataFieldMapper.TypeParser {
@Override @Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { public MetadataFieldMapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
Builder builder = new Builder(); Builder builder = new Builder();
for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) { for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<String, Object> entry = iterator.next(); Map.Entry<String, Object> entry = iterator.next();
@ -123,6 +123,11 @@ public class TTLFieldMapper extends MetadataFieldMapper {
} }
return builder; return builder;
} }
@Override
public MetadataFieldMapper getDefault(Settings indexSettings, MappedFieldType fieldType, String typeName) {
return new TTLFieldMapper(indexSettings);
}
} }
public static final class TTLFieldType extends LongFieldMapper.LongFieldType { public static final class TTLFieldType extends LongFieldMapper.LongFieldType {
@ -157,11 +162,11 @@ public class TTLFieldMapper extends MetadataFieldMapper {
private EnabledAttributeMapper enabledState; private EnabledAttributeMapper enabledState;
private long defaultTTL; private long defaultTTL;
public TTLFieldMapper(Settings indexSettings) { private TTLFieldMapper(Settings indexSettings) {
this(Defaults.TTL_FIELD_TYPE.clone(), Defaults.ENABLED_STATE, Defaults.DEFAULT, null, indexSettings); this(Defaults.TTL_FIELD_TYPE.clone(), Defaults.ENABLED_STATE, Defaults.DEFAULT, null, indexSettings);
} }
protected TTLFieldMapper(MappedFieldType fieldType, EnabledAttributeMapper enabled, long defaultTTL, private TTLFieldMapper(MappedFieldType fieldType, EnabledAttributeMapper enabled, long defaultTTL,
@Nullable Settings fieldDataSettings, Settings indexSettings) { @Nullable Settings fieldDataSettings, Settings indexSettings) {
super(NAME, fieldType, Defaults.TTL_FIELD_TYPE, indexSettings); super(NAME, fieldType, Defaults.TTL_FIELD_TYPE, indexSettings);
this.enabledState = enabled; this.enabledState = enabled;

View File

@ -165,9 +165,9 @@ public class TimestampFieldMapper extends MetadataFieldMapper {
} }
} }
public static class TypeParser implements Mapper.TypeParser { public static class TypeParser implements MetadataFieldMapper.TypeParser {
@Override @Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { public MetadataFieldMapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
Builder builder = new Builder(parserContext.mapperService().fullName(NAME)); Builder builder = new Builder(parserContext.mapperService().fullName(NAME));
if (parserContext.indexVersionCreated().before(Version.V_2_0_0_beta1)) { if (parserContext.indexVersionCreated().before(Version.V_2_0_0_beta1)) {
parseField(builder, builder.name, node, parserContext); parseField(builder, builder.name, node, parserContext);
@ -218,6 +218,11 @@ public class TimestampFieldMapper extends MetadataFieldMapper {
return builder; return builder;
} }
@Override
public MetadataFieldMapper getDefault(Settings indexSettings, MappedFieldType fieldType, String typeName) {
return new TimestampFieldMapper(indexSettings, fieldType);
}
} }
public static final class TimestampFieldType extends DateFieldMapper.DateFieldType { public static final class TimestampFieldType extends DateFieldMapper.DateFieldType {
@ -255,11 +260,11 @@ public class TimestampFieldMapper extends MetadataFieldMapper {
private final String defaultTimestamp; private final String defaultTimestamp;
private final Boolean ignoreMissing; private final Boolean ignoreMissing;
public TimestampFieldMapper(Settings indexSettings, MappedFieldType existing) { private TimestampFieldMapper(Settings indexSettings, MappedFieldType existing) {
this(chooseFieldType(indexSettings, existing).clone(), chooseFieldType(indexSettings, null), Defaults.ENABLED, Defaults.PATH, Defaults.DEFAULT_TIMESTAMP, null, indexSettings); this(chooseFieldType(indexSettings, existing).clone(), chooseFieldType(indexSettings, null), Defaults.ENABLED, Defaults.PATH, Defaults.DEFAULT_TIMESTAMP, null, indexSettings);
} }
protected TimestampFieldMapper(MappedFieldType fieldType, MappedFieldType defaultFieldType, EnabledAttributeMapper enabledState, String path, private TimestampFieldMapper(MappedFieldType fieldType, MappedFieldType defaultFieldType, EnabledAttributeMapper enabledState, String path,
String defaultTimestamp, Boolean ignoreMissing, Settings indexSettings) { String defaultTimestamp, Boolean ignoreMissing, Settings indexSettings) {
super(NAME, fieldType, defaultFieldType, indexSettings); super(NAME, fieldType, defaultFieldType, indexSettings);
this.enabledState = enabledState; this.enabledState = enabledState;

View File

@ -93,9 +93,9 @@ public class TypeFieldMapper extends MetadataFieldMapper {
} }
} }
public static class TypeParser implements Mapper.TypeParser { public static class TypeParser implements MetadataFieldMapper.TypeParser {
@Override @Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { public MetadataFieldMapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
if (parserContext.indexVersionCreated().onOrAfter(Version.V_2_0_0_beta1)) { if (parserContext.indexVersionCreated().onOrAfter(Version.V_2_0_0_beta1)) {
throw new MapperParsingException(NAME + " is not configurable"); throw new MapperParsingException(NAME + " is not configurable");
} }
@ -103,6 +103,11 @@ public class TypeFieldMapper extends MetadataFieldMapper {
parseField(builder, builder.name, node, parserContext); parseField(builder, builder.name, node, parserContext);
return builder; return builder;
} }
@Override
public MetadataFieldMapper getDefault(Settings indexSettings, MappedFieldType fieldType, String typeName) {
return new TypeFieldMapper(indexSettings, fieldType);
}
} }
static final class TypeFieldType extends MappedFieldType { static final class TypeFieldType extends MappedFieldType {
@ -147,12 +152,12 @@ public class TypeFieldMapper extends MetadataFieldMapper {
} }
} }
public TypeFieldMapper(Settings indexSettings, MappedFieldType existing) { private TypeFieldMapper(Settings indexSettings, MappedFieldType existing) {
this(existing == null ? defaultFieldType(indexSettings) : existing.clone(), this(existing == null ? defaultFieldType(indexSettings) : existing.clone(),
indexSettings); indexSettings);
} }
public TypeFieldMapper(MappedFieldType fieldType, Settings indexSettings) { private TypeFieldMapper(MappedFieldType fieldType, Settings indexSettings) {
super(NAME, fieldType, defaultFieldType(indexSettings), indexSettings); super(NAME, fieldType, defaultFieldType(indexSettings), indexSettings);
} }

View File

@ -92,9 +92,9 @@ public class UidFieldMapper extends MetadataFieldMapper {
} }
} }
public static class TypeParser implements Mapper.TypeParser { public static class TypeParser implements MetadataFieldMapper.TypeParser {
@Override @Override
public Mapper.Builder<?, ?> parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { public MetadataFieldMapper.Builder<?, ?> parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
if (parserContext.indexVersionCreated().onOrAfter(Version.V_2_0_0_beta1)) { if (parserContext.indexVersionCreated().onOrAfter(Version.V_2_0_0_beta1)) {
throw new MapperParsingException(NAME + " is not configurable"); throw new MapperParsingException(NAME + " is not configurable");
} }
@ -102,6 +102,11 @@ public class UidFieldMapper extends MetadataFieldMapper {
parseField(builder, builder.name, node, parserContext); parseField(builder, builder.name, node, parserContext);
return builder; return builder;
} }
@Override
public MetadataFieldMapper getDefault(Settings indexSettings, MappedFieldType fieldType, String typeName) {
return new UidFieldMapper(indexSettings, fieldType);
}
} }
static final class UidFieldType extends MappedFieldType { static final class UidFieldType extends MappedFieldType {
@ -133,11 +138,11 @@ public class UidFieldMapper extends MetadataFieldMapper {
} }
} }
public UidFieldMapper(Settings indexSettings, MappedFieldType existing) { private UidFieldMapper(Settings indexSettings, MappedFieldType existing) {
this(existing == null ? Defaults.FIELD_TYPE.clone() : existing, Defaults.FIELD_TYPE, indexSettings); this(existing == null ? Defaults.FIELD_TYPE.clone() : existing, Defaults.FIELD_TYPE, indexSettings);
} }
protected UidFieldMapper(MappedFieldType fieldType, MappedFieldType defaultFieldType, Settings indexSettings) { private UidFieldMapper(MappedFieldType fieldType, MappedFieldType defaultFieldType, Settings indexSettings) {
super(NAME, fieldType, defaultFieldType, indexSettings); super(NAME, fieldType, defaultFieldType, indexSettings);
} }

View File

@ -72,9 +72,9 @@ public class VersionFieldMapper extends MetadataFieldMapper {
} }
} }
public static class TypeParser implements Mapper.TypeParser { public static class TypeParser implements MetadataFieldMapper.TypeParser {
@Override @Override
public Mapper.Builder<?, ?> parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { public MetadataFieldMapper.Builder<?, ?> parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
Builder builder = new Builder(); Builder builder = new Builder();
for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) { for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<String, Object> entry = iterator.next(); Map.Entry<String, Object> entry = iterator.next();
@ -86,6 +86,11 @@ public class VersionFieldMapper extends MetadataFieldMapper {
} }
return builder; return builder;
} }
@Override
public MetadataFieldMapper getDefault(Settings indexSettings, MappedFieldType fieldType, String typeName) {
return new VersionFieldMapper(indexSettings);
}
} }
static final class VersionFieldType extends MappedFieldType { static final class VersionFieldType extends MappedFieldType {
@ -118,7 +123,7 @@ public class VersionFieldMapper extends MetadataFieldMapper {
} }
} }
public VersionFieldMapper(Settings indexSettings) { private VersionFieldMapper(Settings indexSettings) {
super(NAME, Defaults.FIELD_TYPE, Defaults.FIELD_TYPE, indexSettings); super(NAME, Defaults.FIELD_TYPE, Defaults.FIELD_TYPE, indexSettings);
} }

View File

@ -31,6 +31,7 @@ import org.elasticsearch.common.Explicit;
import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Numbers; import org.elasticsearch.common.Numbers;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.network.Cidrs;
import org.elasticsearch.common.network.InetAddresses; import org.elasticsearch.common.network.InetAddresses;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.Fuzziness; import org.elasticsearch.common.unit.Fuzziness;
@ -48,6 +49,7 @@ import org.elasticsearch.index.mapper.core.LongFieldMapper;
import org.elasticsearch.index.mapper.core.LongFieldMapper.CustomLongNumericField; import org.elasticsearch.index.mapper.core.LongFieldMapper.CustomLongNumericField;
import org.elasticsearch.index.mapper.core.NumberFieldMapper; import org.elasticsearch.index.mapper.core.NumberFieldMapper;
import org.elasticsearch.index.query.QueryShardContext; import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.search.aggregations.bucket.range.ipv4.InternalIPv4Range;
import java.io.IOException; import java.io.IOException;
import java.util.Iterator; import java.util.Iterator;
@ -76,7 +78,6 @@ public class IpFieldMapper extends NumberFieldMapper {
} }
private static final Pattern pattern = Pattern.compile("\\."); private static final Pattern pattern = Pattern.compile("\\.");
private static final Pattern MASK_PATTERN = Pattern.compile("(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,3})");
public static long ipToLong(String ip) { public static long ipToLong(String ip) {
try { try {
@ -97,64 +98,6 @@ public class IpFieldMapper extends NumberFieldMapper {
} }
} }
/**
* Computes the min &amp; max ip addresses (represented as long values -
* same way as stored in index) represented by the given CIDR mask
* expression. The returned array has the length of 2, where the first entry
* represents the {@code min} address and the second the {@code max}. A
* {@code -1} value for either the {@code min} or the {@code max},
* represents an unbounded end. In other words:
*
* <p>
* {@code min == -1 == "0.0.0.0" }
* </p>
*
* and
*
* <p>
* {@code max == -1 == "255.255.255.255" }
* </p>
*/
public static long[] cidrMaskToMinMax(String cidr) {
Matcher matcher = MASK_PATTERN.matcher(cidr);
if (!matcher.matches()) {
return null;
}
int addr = ((Integer.parseInt(matcher.group(1)) << 24) & 0xFF000000) | ((Integer.parseInt(matcher.group(2)) << 16) & 0xFF0000)
| ((Integer.parseInt(matcher.group(3)) << 8) & 0xFF00) | (Integer.parseInt(matcher.group(4)) & 0xFF);
int mask = (-1) << (32 - Integer.parseInt(matcher.group(5)));
if (Integer.parseInt(matcher.group(5)) == 0) {
mask = 0 << 32;
}
int from = addr & mask;
long longFrom = intIpToLongIp(from);
if (longFrom == 0) {
longFrom = -1;
}
int to = from + (~mask);
long longTo = intIpToLongIp(to) + 1; // we have to +1 here as the range
// is non-inclusive on the "to"
// side
if (longTo == MAX_IP) {
longTo = -1;
}
return new long[] { longFrom, longTo };
}
private static long intIpToLongIp(int i) {
long p1 = ((long) ((i >> 24) & 0xFF)) << 24;
int p2 = ((i >> 16) & 0xFF) << 16;
int p3 = ((i >> 8) & 0xFF) << 8;
int p4 = i & 0xFF;
return p1 + p2 + p3 + p4;
}
public static class Defaults extends NumberFieldMapper.Defaults { public static class Defaults extends NumberFieldMapper.Defaults {
public static final String NULL_VALUE = null; public static final String NULL_VALUE = null;
@ -274,13 +217,13 @@ public class IpFieldMapper extends NumberFieldMapper {
if (value != null) { if (value != null) {
long[] fromTo; long[] fromTo;
if (value instanceof BytesRef) { if (value instanceof BytesRef) {
fromTo = cidrMaskToMinMax(((BytesRef) value).utf8ToString()); fromTo = Cidrs.cidrMaskToMinMax(((BytesRef) value).utf8ToString());
} else { } else {
fromTo = cidrMaskToMinMax(value.toString()); fromTo = Cidrs.cidrMaskToMinMax(value.toString());
} }
if (fromTo != null) { if (fromTo != null) {
return rangeQuery(fromTo[0] < 0 ? null : fromTo[0], return rangeQuery(fromTo[0] == 0 ? null : fromTo[0],
fromTo[1] < 0 ? null : fromTo[1], true, false); fromTo[1] == InternalIPv4Range.MAX_IP ? null : fromTo[1], true, false);
} }
} }
return super.termQuery(value, context); return super.termQuery(value, context);

View File

@ -67,9 +67,9 @@ public abstract class AbstractQueryBuilder<QB extends AbstractQueryBuilder> exte
protected abstract void doXContent(XContentBuilder builder, Params params) throws IOException; protected abstract void doXContent(XContentBuilder builder, Params params) throws IOException;
protected void printBoostAndQueryName(XContentBuilder builder) throws IOException { protected void printBoostAndQueryName(XContentBuilder builder) throws IOException {
builder.field("boost", boost); builder.field(BOOST_FIELD.getPreferredName(), boost);
if (queryName != null) { if (queryName != null) {
builder.field("_name", queryName); builder.field(NAME_FIELD.getPreferredName(), queryName);
} }
} }
@ -107,7 +107,7 @@ public abstract class AbstractQueryBuilder<QB extends AbstractQueryBuilder> exte
protected abstract Query doToQuery(QueryShardContext context) throws IOException; protected abstract Query doToQuery(QueryShardContext context) throws IOException;
/** /**
* Returns the query name for the query. * Sets the query name for the query.
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
@ -117,7 +117,7 @@ public abstract class AbstractQueryBuilder<QB extends AbstractQueryBuilder> exte
} }
/** /**
* Sets the query name for the query. * Returns the query name for the query.
*/ */
@Override @Override
public final String queryName() { public final String queryName() {

View File

@ -20,6 +20,7 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.StreamOutput;
@ -30,6 +31,8 @@ import java.util.Objects;
public abstract class BaseTermQueryBuilder<QB extends BaseTermQueryBuilder<QB>> extends AbstractQueryBuilder<QB> { public abstract class BaseTermQueryBuilder<QB extends BaseTermQueryBuilder<QB>> extends AbstractQueryBuilder<QB> {
public static final ParseField VALUE_FIELD = new ParseField("value");
/** Name of field to match against. */ /** Name of field to match against. */
protected final String fieldName; protected final String fieldName;
@ -133,7 +136,7 @@ public abstract class BaseTermQueryBuilder<QB extends BaseTermQueryBuilder<QB>>
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(getName()); builder.startObject(getName());
builder.startObject(fieldName); builder.startObject(fieldName);
builder.field("value", convertToStringIfBytesRef(this.value)); builder.field(VALUE_FIELD.getPreferredName(), convertToStringIfBytesRef(this.value));
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
builder.endObject(); builder.endObject();
builder.endObject(); builder.endObject();

View File

@ -231,14 +231,14 @@ public class BoolQueryBuilder extends AbstractQueryBuilder<BoolQueryBuilder> {
@Override @Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
doXArrayContent("must", mustClauses, builder, params); doXArrayContent(BoolQueryParser.MUST, mustClauses, builder, params);
doXArrayContent("filter", filterClauses, builder, params); doXArrayContent(BoolQueryParser.FILTER, filterClauses, builder, params);
doXArrayContent("must_not", mustNotClauses, builder, params); doXArrayContent(BoolQueryParser.MUST_NOT, mustNotClauses, builder, params);
doXArrayContent("should", shouldClauses, builder, params); doXArrayContent(BoolQueryParser.SHOULD, shouldClauses, builder, params);
builder.field("disable_coord", disableCoord); builder.field(BoolQueryParser.DISABLE_COORD_FIELD.getPreferredName(), disableCoord);
builder.field("adjust_pure_negative", adjustPureNegative); builder.field(BoolQueryParser.ADJUST_PURE_NEGATIVE.getPreferredName(), adjustPureNegative);
if (minimumShouldMatch != null) { if (minimumShouldMatch != null) {
builder.field("minimum_should_match", minimumShouldMatch); builder.field(BoolQueryParser.MINIMUM_SHOULD_MATCH.getPreferredName(), minimumShouldMatch);
} }
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
builder.endObject(); builder.endObject();

View File

@ -20,6 +20,7 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.BooleanQuery;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
@ -34,6 +35,16 @@ import java.util.List;
*/ */
public class BoolQueryParser implements QueryParser<BoolQueryBuilder> { public class BoolQueryParser implements QueryParser<BoolQueryBuilder> {
public static final String MUSTNOT = "mustNot";
public static final String MUST_NOT = "must_not";
public static final String FILTER = "filter";
public static final String SHOULD = "should";
public static final String MUST = "must";
public static final ParseField DISABLE_COORD_FIELD = new ParseField("disable_coord");
public static final ParseField MINIMUM_SHOULD_MATCH = new ParseField("minimum_should_match");
public static final ParseField MINIMUM_NUMBER_SHOULD_MATCH = new ParseField("minimum_number_should_match");
public static final ParseField ADJUST_PURE_NEGATIVE = new ParseField("adjust_pure_negative");
@Inject @Inject
public BoolQueryParser(Settings settings) { public BoolQueryParser(Settings settings) {
BooleanQuery.setMaxClauseCount(settings.getAsInt("index.query.bool.max_clause_count", settings.getAsInt("indices.query.bool.max_clause_count", BooleanQuery.getMaxClauseCount()))); BooleanQuery.setMaxClauseCount(settings.getAsInt("index.query.bool.max_clause_count", settings.getAsInt("indices.query.bool.max_clause_count", BooleanQuery.getMaxClauseCount())));
@ -69,20 +80,20 @@ public class BoolQueryParser implements QueryParser<BoolQueryBuilder> {
// skip // skip
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
switch (currentFieldName) { switch (currentFieldName) {
case "must": case MUST:
query = parseContext.parseInnerQueryBuilder(); query = parseContext.parseInnerQueryBuilder();
mustClauses.add(query); mustClauses.add(query);
break; break;
case "should": case SHOULD:
query = parseContext.parseInnerQueryBuilder(); query = parseContext.parseInnerQueryBuilder();
shouldClauses.add(query); shouldClauses.add(query);
break; break;
case "filter": case FILTER:
query = parseContext.parseInnerQueryBuilder(); query = parseContext.parseInnerQueryBuilder();
filterClauses.add(query); filterClauses.add(query);
break; break;
case "must_not": case MUST_NOT:
case "mustNot": case MUSTNOT:
query = parseContext.parseInnerQueryBuilder(); query = parseContext.parseInnerQueryBuilder();
mustNotClauses.add(query); mustNotClauses.add(query);
break; break;
@ -92,20 +103,20 @@ public class BoolQueryParser implements QueryParser<BoolQueryBuilder> {
} else if (token == XContentParser.Token.START_ARRAY) { } else if (token == XContentParser.Token.START_ARRAY) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
switch (currentFieldName) { switch (currentFieldName) {
case "must": case MUST:
query = parseContext.parseInnerQueryBuilder(); query = parseContext.parseInnerQueryBuilder();
mustClauses.add(query); mustClauses.add(query);
break; break;
case "should": case SHOULD:
query = parseContext.parseInnerQueryBuilder(); query = parseContext.parseInnerQueryBuilder();
shouldClauses.add(query); shouldClauses.add(query);
break; break;
case "filter": case FILTER:
query = parseContext.parseInnerQueryBuilder(); query = parseContext.parseInnerQueryBuilder();
filterClauses.add(query); filterClauses.add(query);
break; break;
case "must_not": case MUST_NOT:
case "mustNot": case MUSTNOT:
query = parseContext.parseInnerQueryBuilder(); query = parseContext.parseInnerQueryBuilder();
mustNotClauses.add(query); mustNotClauses.add(query);
break; break;
@ -114,17 +125,17 @@ public class BoolQueryParser implements QueryParser<BoolQueryBuilder> {
} }
} }
} else if (token.isValue()) { } else if (token.isValue()) {
if ("disable_coord".equals(currentFieldName) || "disableCoord".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, DISABLE_COORD_FIELD)) {
disableCoord = parser.booleanValue(); disableCoord = parser.booleanValue();
} else if ("minimum_should_match".equals(currentFieldName) || "minimumShouldMatch".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, MINIMUM_SHOULD_MATCH)) {
minimumShouldMatch = parser.textOrNull(); minimumShouldMatch = parser.textOrNull();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else if ("minimum_number_should_match".equals(currentFieldName) || "minimumNumberShouldMatch".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, MINIMUM_NUMBER_SHOULD_MATCH)) {
minimumShouldMatch = parser.textOrNull(); minimumShouldMatch = parser.textOrNull();
} else if ("adjust_pure_negative".equals(currentFieldName) || "adjustPureNegative".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, ADJUST_PURE_NEGATIVE)) {
adjustPureNegative = parser.booleanValue(); adjustPureNegative = parser.booleanValue();
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[bool] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[bool] query does not support [" + currentFieldName + "]");

View File

@ -104,11 +104,11 @@ public class BoostingQueryBuilder extends AbstractQueryBuilder<BoostingQueryBuil
@Override @Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.field("positive"); builder.field(BoostingQueryParser.POSITIVE_FIELD.getPreferredName());
positiveQuery.toXContent(builder, params); positiveQuery.toXContent(builder, params);
builder.field("negative"); builder.field(BoostingQueryParser.NEGATIVE_FIELD.getPreferredName());
negativeQuery.toXContent(builder, params); negativeQuery.toXContent(builder, params);
builder.field("negative_boost", negativeBoost); builder.field(BoostingQueryParser.NEGATIVE_BOOST_FIELD.getPreferredName(), negativeBoost);
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
builder.endObject(); builder.endObject();
} }

View File

@ -19,6 +19,7 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
@ -29,6 +30,10 @@ import java.io.IOException;
*/ */
public class BoostingQueryParser implements QueryParser<BoostingQueryBuilder> { public class BoostingQueryParser implements QueryParser<BoostingQueryBuilder> {
public static final ParseField POSITIVE_FIELD = new ParseField("positive");
public static final ParseField NEGATIVE_FIELD = new ParseField("negative");
public static final ParseField NEGATIVE_BOOST_FIELD = new ParseField("negative_boost");
@Override @Override
public String[] names() { public String[] names() {
return new String[]{BoostingQueryBuilder.NAME}; return new String[]{BoostingQueryBuilder.NAME};
@ -52,21 +57,21 @@ public class BoostingQueryParser implements QueryParser<BoostingQueryBuilder> {
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
if ("positive".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, POSITIVE_FIELD)) {
positiveQuery = parseContext.parseInnerQueryBuilder(); positiveQuery = parseContext.parseInnerQueryBuilder();
positiveQueryFound = true; positiveQueryFound = true;
} else if ("negative".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, NEGATIVE_FIELD)) {
negativeQuery = parseContext.parseInnerQueryBuilder(); negativeQuery = parseContext.parseInnerQueryBuilder();
negativeQueryFound = true; negativeQueryFound = true;
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[boosting] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[boosting] query does not support [" + currentFieldName + "]");
} }
} else if (token.isValue()) { } else if (token.isValue()) {
if ("negative_boost".equals(currentFieldName) || "negativeBoost".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, NEGATIVE_BOOST_FIELD)) {
negativeBoost = parser.floatValue(); negativeBoost = parser.floatValue();
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[boosting] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[boosting] query does not support [" + currentFieldName + "]");

View File

@ -202,21 +202,21 @@ public class CommonTermsQueryBuilder extends AbstractQueryBuilder<CommonTermsQue
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.startObject(fieldName); builder.startObject(fieldName);
builder.field("query", text); builder.field(CommonTermsQueryParser.QUERY_FIELD.getPreferredName(), text);
builder.field("disable_coord", disableCoord); builder.field(CommonTermsQueryParser.DISABLE_COORD_FIELD.getPreferredName(), disableCoord);
builder.field("high_freq_operator", highFreqOperator.toString()); builder.field(CommonTermsQueryParser.HIGH_FREQ_OPERATOR_FIELD.getPreferredName(), highFreqOperator.toString());
builder.field("low_freq_operator", lowFreqOperator.toString()); builder.field(CommonTermsQueryParser.LOW_FREQ_OPERATOR_FIELD.getPreferredName(), lowFreqOperator.toString());
if (analyzer != null) { if (analyzer != null) {
builder.field("analyzer", analyzer); builder.field(CommonTermsQueryParser.ANALYZER_FIELD.getPreferredName(), analyzer);
} }
builder.field("cutoff_frequency", cutoffFrequency); builder.field(CommonTermsQueryParser.CUTOFF_FREQUENCY_FIELD.getPreferredName(), cutoffFrequency);
if (lowFreqMinimumShouldMatch != null || highFreqMinimumShouldMatch != null) { if (lowFreqMinimumShouldMatch != null || highFreqMinimumShouldMatch != null) {
builder.startObject("minimum_should_match"); builder.startObject(CommonTermsQueryParser.MINIMUM_SHOULD_MATCH_FIELD.getPreferredName());
if (lowFreqMinimumShouldMatch != null) { if (lowFreqMinimumShouldMatch != null) {
builder.field("low_freq", lowFreqMinimumShouldMatch); builder.field(CommonTermsQueryParser.LOW_FREQ_FIELD.getPreferredName(), lowFreqMinimumShouldMatch);
} }
if (highFreqMinimumShouldMatch != null) { if (highFreqMinimumShouldMatch != null) {
builder.field("high_freq", highFreqMinimumShouldMatch); builder.field(CommonTermsQueryParser.HIGH_FREQ_FIELD.getPreferredName(), highFreqMinimumShouldMatch);
} }
builder.endObject(); builder.endObject();
} }

View File

@ -19,6 +19,7 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
@ -29,6 +30,16 @@ import java.io.IOException;
*/ */
public class CommonTermsQueryParser implements QueryParser<CommonTermsQueryBuilder> { public class CommonTermsQueryParser implements QueryParser<CommonTermsQueryBuilder> {
public static final ParseField CUTOFF_FREQUENCY_FIELD = new ParseField("cutoff_frequency");
public static final ParseField MINIMUM_SHOULD_MATCH_FIELD = new ParseField("minimum_should_match");
public static final ParseField LOW_FREQ_OPERATOR_FIELD = new ParseField("low_freq_operator");
public static final ParseField HIGH_FREQ_OPERATOR_FIELD = new ParseField("high_freq_operator");
public static final ParseField DISABLE_COORD_FIELD = new ParseField("disable_coord");
public static final ParseField ANALYZER_FIELD = new ParseField("analyzer");
public static final ParseField QUERY_FIELD = new ParseField("query");
public static final ParseField HIGH_FREQ_FIELD = new ParseField("high_freq");
public static final ParseField LOW_FREQ_FIELD = new ParseField("low_freq");
@Override @Override
public String[] names() { public String[] names() {
return new String[] { CommonTermsQueryBuilder.NAME }; return new String[] { CommonTermsQueryBuilder.NAME };
@ -59,15 +70,15 @@ public class CommonTermsQueryParser implements QueryParser<CommonTermsQueryBuild
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
if ("minimum_should_match".equals(currentFieldName) || "minimumShouldMatch".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, MINIMUM_SHOULD_MATCH_FIELD)) {
String innerFieldName = null; String innerFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
innerFieldName = parser.currentName(); innerFieldName = parser.currentName();
} else if (token.isValue()) { } else if (token.isValue()) {
if ("low_freq".equals(innerFieldName) || "lowFreq".equals(innerFieldName)) { if (parseContext.parseFieldMatcher().match(innerFieldName, LOW_FREQ_FIELD)) {
lowFreqMinimumShouldMatch = parser.text(); lowFreqMinimumShouldMatch = parser.text();
} else if ("high_freq".equals(innerFieldName) || "highFreq".equals(innerFieldName)) { } else if (parseContext.parseFieldMatcher().match(innerFieldName, HIGH_FREQ_FIELD)) {
highFreqMinimumShouldMatch = parser.text(); highFreqMinimumShouldMatch = parser.text();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[" + CommonTermsQueryBuilder.NAME + "] query does not support [" + innerFieldName throw new ParsingException(parser.getTokenLocation(), "[" + CommonTermsQueryBuilder.NAME + "] query does not support [" + innerFieldName
@ -82,23 +93,23 @@ public class CommonTermsQueryParser implements QueryParser<CommonTermsQueryBuild
throw new ParsingException(parser.getTokenLocation(), "[" + CommonTermsQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[" + CommonTermsQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]");
} }
} else if (token.isValue()) { } else if (token.isValue()) {
if ("query".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, QUERY_FIELD)) {
text = parser.objectText(); text = parser.objectText();
} else if ("analyzer".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, ANALYZER_FIELD)) {
analyzer = parser.text(); analyzer = parser.text();
} else if ("disable_coord".equals(currentFieldName) || "disableCoord".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, DISABLE_COORD_FIELD)) {
disableCoord = parser.booleanValue(); disableCoord = parser.booleanValue();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else if ("high_freq_operator".equals(currentFieldName) || "highFreqOperator".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, HIGH_FREQ_OPERATOR_FIELD)) {
highFreqOperator = Operator.fromString(parser.text()); highFreqOperator = Operator.fromString(parser.text());
} else if ("low_freq_operator".equals(currentFieldName) || "lowFreqOperator".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, LOW_FREQ_OPERATOR_FIELD)) {
lowFreqOperator = Operator.fromString(parser.text()); lowFreqOperator = Operator.fromString(parser.text());
} else if ("minimum_should_match".equals(currentFieldName) || "minimumShouldMatch".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, MINIMUM_SHOULD_MATCH_FIELD)) {
lowFreqMinimumShouldMatch = parser.text(); lowFreqMinimumShouldMatch = parser.text();
} else if ("cutoff_frequency".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, CUTOFF_FREQUENCY_FIELD)) {
cutoffFrequency = parser.floatValue(); cutoffFrequency = parser.floatValue();
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[" + CommonTermsQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[" + CommonTermsQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]");

View File

@ -63,7 +63,7 @@ public class ConstantScoreQueryBuilder extends AbstractQueryBuilder<ConstantScor
@Override @Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.field("filter"); builder.field(ConstantScoreQueryParser.INNER_QUERY_FIELD.getPreferredName());
filterBuilder.toXContent(builder, params); filterBuilder.toXContent(builder, params);
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
builder.endObject(); builder.endObject();

View File

@ -31,7 +31,7 @@ import java.io.IOException;
*/ */
public class ConstantScoreQueryParser implements QueryParser<ConstantScoreQueryBuilder> { public class ConstantScoreQueryParser implements QueryParser<ConstantScoreQueryBuilder> {
private static final ParseField INNER_QUERY_FIELD = new ParseField("filter", "query"); public static final ParseField INNER_QUERY_FIELD = new ParseField("filter", "query");
@Override @Override
public String[] names() { public String[] names() {
@ -62,9 +62,9 @@ public class ConstantScoreQueryParser implements QueryParser<ConstantScoreQueryB
throw new ParsingException(parser.getTokenLocation(), "[constant_score] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[constant_score] query does not support [" + currentFieldName + "]");
} }
} else if (token.isValue()) { } else if (token.isValue()) {
if ("_name".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[constant_score] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[constant_score] query does not support [" + currentFieldName + "]");

View File

@ -88,8 +88,8 @@ public class DisMaxQueryBuilder extends AbstractQueryBuilder<DisMaxQueryBuilder>
@Override @Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.field("tie_breaker", tieBreaker); builder.field(DisMaxQueryParser.TIE_BREAKER_FIELD.getPreferredName(), tieBreaker);
builder.startArray("queries"); builder.startArray(DisMaxQueryParser.QUERIES_FIELD.getPreferredName());
for (QueryBuilder queryBuilder : queries) { for (QueryBuilder queryBuilder : queries) {
queryBuilder.toXContent(builder, params); queryBuilder.toXContent(builder, params);
} }

View File

@ -19,6 +19,7 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
@ -32,6 +33,9 @@ import java.util.List;
*/ */
public class DisMaxQueryParser implements QueryParser<DisMaxQueryBuilder> { public class DisMaxQueryParser implements QueryParser<DisMaxQueryBuilder> {
public static final ParseField TIE_BREAKER_FIELD = new ParseField("tie_breaker");
public static final ParseField QUERIES_FIELD = new ParseField("queries");
@Override @Override
public String[] names() { public String[] names() {
return new String[]{DisMaxQueryBuilder.NAME, Strings.toCamelCase(DisMaxQueryBuilder.NAME)}; return new String[]{DisMaxQueryBuilder.NAME, Strings.toCamelCase(DisMaxQueryBuilder.NAME)};
@ -54,7 +58,7 @@ public class DisMaxQueryParser implements QueryParser<DisMaxQueryBuilder> {
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
if ("queries".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, QUERIES_FIELD)) {
queriesFound = true; queriesFound = true;
QueryBuilder query = parseContext.parseInnerQueryBuilder(); QueryBuilder query = parseContext.parseInnerQueryBuilder();
queries.add(query); queries.add(query);
@ -62,7 +66,7 @@ public class DisMaxQueryParser implements QueryParser<DisMaxQueryBuilder> {
throw new ParsingException(parser.getTokenLocation(), "[dis_max] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[dis_max] query does not support [" + currentFieldName + "]");
} }
} else if (token == XContentParser.Token.START_ARRAY) { } else if (token == XContentParser.Token.START_ARRAY) {
if ("queries".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, QUERIES_FIELD)) {
queriesFound = true; queriesFound = true;
while (token != XContentParser.Token.END_ARRAY) { while (token != XContentParser.Token.END_ARRAY) {
QueryBuilder query = parseContext.parseInnerQueryBuilder(); QueryBuilder query = parseContext.parseInnerQueryBuilder();
@ -73,11 +77,11 @@ public class DisMaxQueryParser implements QueryParser<DisMaxQueryBuilder> {
throw new ParsingException(parser.getTokenLocation(), "[dis_max] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[dis_max] query does not support [" + currentFieldName + "]");
} }
} else { } else {
if ("boost".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else if ("tie_breaker".equals(currentFieldName) || "tieBreaker".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, TIE_BREAKER_FIELD)) {
tieBreaker = parser.floatValue(); tieBreaker = parser.floatValue();
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[dis_max] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[dis_max] query does not support [" + currentFieldName + "]");

View File

@ -61,7 +61,7 @@ public class ExistsQueryBuilder extends AbstractQueryBuilder<ExistsQueryBuilder>
@Override @Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.field("field", fieldName); builder.field(ExistsQueryParser.FIELD_FIELD.getPreferredName(), fieldName);
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
builder.endObject(); builder.endObject();
} }

View File

@ -19,6 +19,7 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
@ -29,6 +30,8 @@ import java.io.IOException;
*/ */
public class ExistsQueryParser implements QueryParser<ExistsQueryBuilder> { public class ExistsQueryParser implements QueryParser<ExistsQueryBuilder> {
public static final ParseField FIELD_FIELD = new ParseField("field");
@Override @Override
public String[] names() { public String[] names() {
return new String[]{ExistsQueryBuilder.NAME}; return new String[]{ExistsQueryBuilder.NAME};
@ -48,11 +51,11 @@ public class ExistsQueryParser implements QueryParser<ExistsQueryBuilder> {
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token.isValue()) { } else if (token.isValue()) {
if ("field".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, FIELD_FIELD)) {
fieldPattern = parser.text(); fieldPattern = parser.text();
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[" + ExistsQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[" + ExistsQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]");

View File

@ -75,9 +75,9 @@ public class FieldMaskingSpanQueryBuilder extends AbstractQueryBuilder<FieldMask
@Override @Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.field("query"); builder.field(FieldMaskingSpanQueryParser.QUERY_FIELD.getPreferredName());
queryBuilder.toXContent(builder, params); queryBuilder.toXContent(builder, params);
builder.field("field", fieldName); builder.field(FieldMaskingSpanQueryParser.FIELD_FIELD.getPreferredName(), fieldName);
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
builder.endObject(); builder.endObject();
} }

View File

@ -19,6 +19,7 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
@ -29,6 +30,9 @@ import java.io.IOException;
*/ */
public class FieldMaskingSpanQueryParser implements QueryParser<FieldMaskingSpanQueryBuilder> { public class FieldMaskingSpanQueryParser implements QueryParser<FieldMaskingSpanQueryBuilder> {
public static final ParseField FIELD_FIELD = new ParseField("field");
public static final ParseField QUERY_FIELD = new ParseField("query");
@Override @Override
public String[] names() { public String[] names() {
return new String[]{FieldMaskingSpanQueryBuilder.NAME, Strings.toCamelCase(FieldMaskingSpanQueryBuilder.NAME)}; return new String[]{FieldMaskingSpanQueryBuilder.NAME, Strings.toCamelCase(FieldMaskingSpanQueryBuilder.NAME)};
@ -50,7 +54,7 @@ public class FieldMaskingSpanQueryParser implements QueryParser<FieldMaskingSpan
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
if ("query".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, QUERY_FIELD)) {
QueryBuilder query = parseContext.parseInnerQueryBuilder(); QueryBuilder query = parseContext.parseInnerQueryBuilder();
if (!(query instanceof SpanQueryBuilder)) { if (!(query instanceof SpanQueryBuilder)) {
throw new ParsingException(parser.getTokenLocation(), "[field_masking_span] query must be of type span query"); throw new ParsingException(parser.getTokenLocation(), "[field_masking_span] query must be of type span query");
@ -61,11 +65,11 @@ public class FieldMaskingSpanQueryParser implements QueryParser<FieldMaskingSpan
+ currentFieldName + "]"); + currentFieldName + "]");
} }
} else { } else {
if ("boost".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else if ("field".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, FIELD_FIELD)) {
field = parser.text(); field = parser.text();
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[field_masking_span] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[field_masking_span] query does not support [" + currentFieldName + "]");

View File

@ -209,16 +209,16 @@ public class FuzzyQueryBuilder extends AbstractQueryBuilder<FuzzyQueryBuilder> i
} }
@Override @Override
public void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.startObject(fieldName); builder.startObject(fieldName);
builder.field("value", convertToStringIfBytesRef(this.value)); builder.field(FuzzyQueryParser.VALUE_FIELD.getPreferredName(), convertToStringIfBytesRef(this.value));
fuzziness.toXContent(builder, params); fuzziness.toXContent(builder, params);
builder.field("prefix_length", prefixLength); builder.field(FuzzyQueryParser.PREFIX_LENGTH_FIELD.getPreferredName(), prefixLength);
builder.field("max_expansions", maxExpansions); builder.field(FuzzyQueryParser.MAX_EXPANSIONS_FIELD.getPreferredName(), maxExpansions);
builder.field("transpositions", transpositions); builder.field(FuzzyQueryParser.TRANSPOSITIONS_FIELD.getPreferredName(), transpositions);
if (rewrite != null) { if (rewrite != null) {
builder.field("rewrite", rewrite); builder.field(FuzzyQueryParser.REWRITE_FIELD.getPreferredName(), rewrite);
} }
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
builder.endObject(); builder.endObject();
@ -231,7 +231,7 @@ public class FuzzyQueryBuilder extends AbstractQueryBuilder<FuzzyQueryBuilder> i
} }
@Override @Override
public Query doToQuery(QueryShardContext context) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
Query query = null; Query query = null;
String rewrite = this.rewrite; String rewrite = this.rewrite;
if (rewrite == null && context.isFilter()) { if (rewrite == null && context.isFilter()) {
@ -253,7 +253,7 @@ public class FuzzyQueryBuilder extends AbstractQueryBuilder<FuzzyQueryBuilder> i
} }
@Override @Override
public FuzzyQueryBuilder doReadFrom(StreamInput in) throws IOException { protected FuzzyQueryBuilder doReadFrom(StreamInput in) throws IOException {
FuzzyQueryBuilder fuzzyQueryBuilder = new FuzzyQueryBuilder(in.readString(), in.readGenericValue()); FuzzyQueryBuilder fuzzyQueryBuilder = new FuzzyQueryBuilder(in.readString(), in.readGenericValue());
fuzzyQueryBuilder.fuzziness = Fuzziness.readFuzzinessFrom(in); fuzzyQueryBuilder.fuzziness = Fuzziness.readFuzzinessFrom(in);
fuzzyQueryBuilder.prefixLength = in.readVInt(); fuzzyQueryBuilder.prefixLength = in.readVInt();
@ -264,7 +264,7 @@ public class FuzzyQueryBuilder extends AbstractQueryBuilder<FuzzyQueryBuilder> i
} }
@Override @Override
public void doWriteTo(StreamOutput out) throws IOException { protected void doWriteTo(StreamOutput out) throws IOException {
out.writeString(this.fieldName); out.writeString(this.fieldName);
out.writeGenericValue(this.value); out.writeGenericValue(this.value);
this.fuzziness.writeTo(out); this.fuzziness.writeTo(out);
@ -275,12 +275,12 @@ public class FuzzyQueryBuilder extends AbstractQueryBuilder<FuzzyQueryBuilder> i
} }
@Override @Override
public int doHashCode() { protected int doHashCode() {
return Objects.hash(fieldName, value, fuzziness, prefixLength, maxExpansions, transpositions, rewrite); return Objects.hash(fieldName, value, fuzziness, prefixLength, maxExpansions, transpositions, rewrite);
} }
@Override @Override
public boolean doEquals(FuzzyQueryBuilder other) { protected boolean doEquals(FuzzyQueryBuilder other) {
return Objects.equals(fieldName, other.fieldName) && return Objects.equals(fieldName, other.fieldName) &&
Objects.equals(value, other.value) && Objects.equals(value, other.value) &&
Objects.equals(fuzziness, other.fuzziness) && Objects.equals(fuzziness, other.fuzziness) &&

View File

@ -19,6 +19,7 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.unit.Fuzziness; import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
@ -27,6 +28,13 @@ import java.io.IOException;
public class FuzzyQueryParser implements QueryParser<FuzzyQueryBuilder> { public class FuzzyQueryParser implements QueryParser<FuzzyQueryBuilder> {
public static final ParseField TERM_FIELD = new ParseField("term");
public static final ParseField VALUE_FIELD = new ParseField("value");
public static final ParseField PREFIX_LENGTH_FIELD = new ParseField("prefix_length");
public static final ParseField MAX_EXPANSIONS_FIELD = new ParseField("max_expansions");
public static final ParseField TRANSPOSITIONS_FIELD = new ParseField("transpositions");
public static final ParseField REWRITE_FIELD = new ParseField("rewrite");
@Override @Override
public String[] names() { public String[] names() {
return new String[]{ FuzzyQueryBuilder.NAME }; return new String[]{ FuzzyQueryBuilder.NAME };
@ -60,23 +68,23 @@ public class FuzzyQueryParser implements QueryParser<FuzzyQueryBuilder> {
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else { } else {
if ("term".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, TERM_FIELD)) {
value = parser.objectBytes(); value = parser.objectBytes();
} else if ("value".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, VALUE_FIELD)) {
value = parser.objectBytes(); value = parser.objectBytes();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else if (parseContext.parseFieldMatcher().match(currentFieldName, Fuzziness.FIELD)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, Fuzziness.FIELD)) {
fuzziness = Fuzziness.parse(parser); fuzziness = Fuzziness.parse(parser);
} else if ("prefix_length".equals(currentFieldName) || "prefixLength".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, PREFIX_LENGTH_FIELD)) {
prefixLength = parser.intValue(); prefixLength = parser.intValue();
} else if ("max_expansions".equals(currentFieldName) || "maxExpansions".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, MAX_EXPANSIONS_FIELD)) {
maxExpansions = parser.intValue(); maxExpansions = parser.intValue();
} else if ("transpositions".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, TRANSPOSITIONS_FIELD)) {
transpositions = parser.booleanValue(); transpositions = parser.booleanValue();
} else if ("rewrite".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, REWRITE_FIELD)) {
rewrite = parser.textOrNull(); rewrite = parser.textOrNull();
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[fuzzy] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[fuzzy] query does not support [" + currentFieldName + "]");

View File

@ -292,11 +292,11 @@ public class GeoBoundingBoxQueryBuilder extends AbstractQueryBuilder<GeoBounding
builder.startObject(NAME); builder.startObject(NAME);
builder.startObject(fieldName); builder.startObject(fieldName);
builder.array(GeoBoundingBoxQueryParser.TOP_LEFT, topLeft.getLon(), topLeft.getLat()); builder.array(GeoBoundingBoxQueryParser.TOP_LEFT_FIELD.getPreferredName(), topLeft.getLon(), topLeft.getLat());
builder.array(GeoBoundingBoxQueryParser.BOTTOM_RIGHT, bottomRight.getLon(), bottomRight.getLat()); builder.array(GeoBoundingBoxQueryParser.BOTTOM_RIGHT_FIELD.getPreferredName(), bottomRight.getLon(), bottomRight.getLat());
builder.endObject(); builder.endObject();
builder.field("validation_method", validationMethod); builder.field(GeoBoundingBoxQueryParser.VALIDATION_METHOD_FIELD.getPreferredName(), validationMethod);
builder.field("type", type); builder.field(GeoBoundingBoxQueryParser.TYPE_FIELD.getPreferredName(), type);
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
@ -304,7 +304,7 @@ public class GeoBoundingBoxQueryBuilder extends AbstractQueryBuilder<GeoBounding
} }
@Override @Override
public boolean doEquals(GeoBoundingBoxQueryBuilder other) { protected boolean doEquals(GeoBoundingBoxQueryBuilder other) {
return Objects.equals(topLeft, other.topLeft) && return Objects.equals(topLeft, other.topLeft) &&
Objects.equals(bottomRight, other.bottomRight) && Objects.equals(bottomRight, other.bottomRight) &&
Objects.equals(type, other.type) && Objects.equals(type, other.type) &&
@ -313,12 +313,12 @@ public class GeoBoundingBoxQueryBuilder extends AbstractQueryBuilder<GeoBounding
} }
@Override @Override
public int doHashCode() { protected int doHashCode() {
return Objects.hash(topLeft, bottomRight, type, validationMethod, fieldName); return Objects.hash(topLeft, bottomRight, type, validationMethod, fieldName);
} }
@Override @Override
public GeoBoundingBoxQueryBuilder doReadFrom(StreamInput in) throws IOException { protected GeoBoundingBoxQueryBuilder doReadFrom(StreamInput in) throws IOException {
String fieldName = in.readString(); String fieldName = in.readString();
GeoBoundingBoxQueryBuilder geo = new GeoBoundingBoxQueryBuilder(fieldName); GeoBoundingBoxQueryBuilder geo = new GeoBoundingBoxQueryBuilder(fieldName);
geo.topLeft = in.readGeoPoint(); geo.topLeft = in.readGeoPoint();
@ -329,7 +329,7 @@ public class GeoBoundingBoxQueryBuilder extends AbstractQueryBuilder<GeoBounding
} }
@Override @Override
public void doWriteTo(StreamOutput out) throws IOException { protected void doWriteTo(StreamOutput out) throws IOException {
out.writeString(fieldName); out.writeString(fieldName);
out.writeGeoPoint(topLeft); out.writeGeoPoint(topLeft);
out.writeGeoPoint(bottomRight); out.writeGeoPoint(bottomRight);

View File

@ -20,6 +20,7 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.geo.GeoPoint; import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.geo.GeoUtils; import org.elasticsearch.common.geo.GeoUtils;
@ -31,34 +32,19 @@ public class GeoBoundingBoxQueryParser implements QueryParser<GeoBoundingBoxQuer
public static final String NAME = "geo_bbox"; public static final String NAME = "geo_bbox";
/** Key to refer to the top of the bounding box. */ public static final ParseField IGNORE_MALFORMED_FIELD = new ParseField("ignore_malformed");
public static final String TOP = "top"; public static final ParseField TYPE_FIELD = new ParseField("type");
/** Key to refer to the left of the bounding box. */ public static final ParseField VALIDATION_METHOD_FIELD = new ParseField("validation_method");
public static final String LEFT = "left"; public static final ParseField COERCE_FIELD = new ParseField("coerce", "normalize");
/** Key to refer to the right of the bounding box. */ public static final ParseField FIELD_FIELD = new ParseField("field");
public static final String RIGHT = "right"; public static final ParseField TOP_FIELD = new ParseField("top");
/** Key to refer to the bottom of the bounding box. */ public static final ParseField BOTTOM_FIELD = new ParseField("bottom");
public static final String BOTTOM = "bottom"; public static final ParseField LEFT_FIELD = new ParseField("left");
public static final ParseField RIGHT_FIELD = new ParseField("right");
/** Key to refer to top_left corner of bounding box. */ public static final ParseField TOP_LEFT_FIELD = new ParseField("top_left");
public static final String TOP_LEFT = TOP + "_" + LEFT; public static final ParseField BOTTOM_RIGHT_FIELD = new ParseField("bottom_right");
/** Key to refer to bottom_right corner of bounding box. */ public static final ParseField TOP_RIGHT_FIELD = new ParseField("top_right");
public static final String BOTTOM_RIGHT = BOTTOM + "_" + RIGHT; public static final ParseField BOTTOM_LEFT_FIELD = new ParseField("bottom_left");
/** Key to refer to top_right corner of bounding box. */
public static final String TOP_RIGHT = TOP + "_" + RIGHT;
/** Key to refer to bottom left corner of bounding box. */
public static final String BOTTOM_LEFT = BOTTOM + "_" + LEFT;
/** Key to refer to top_left corner of bounding box. */
public static final String TOPLEFT = "topLeft";
/** Key to refer to bottom_right corner of bounding box. */
public static final String BOTTOMRIGHT = "bottomRight";
/** Key to refer to top_right corner of bounding box. */
public static final String TOPRIGHT = "topRight";
/** Key to refer to bottom left corner of bounding box. */
public static final String BOTTOMLEFT = "bottomLeft";
public static final String FIELD = "field";
@Override @Override
public String[] names() { public String[] names() {
@ -100,30 +86,30 @@ public class GeoBoundingBoxQueryParser implements QueryParser<GeoBoundingBoxQuer
token = parser.nextToken(); token = parser.nextToken();
if (parseContext.isDeprecatedSetting(currentFieldName)) { if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip // skip
} else if (FIELD.equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, FIELD_FIELD)) {
fieldName = parser.text(); fieldName = parser.text();
} else if (TOP.equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, TOP_FIELD)) {
top = parser.doubleValue(); top = parser.doubleValue();
} else if (BOTTOM.equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, BOTTOM_FIELD)) {
bottom = parser.doubleValue(); bottom = parser.doubleValue();
} else if (LEFT.equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, LEFT_FIELD)) {
left = parser.doubleValue(); left = parser.doubleValue();
} else if (RIGHT.equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, RIGHT_FIELD)) {
right = parser.doubleValue(); right = parser.doubleValue();
} else { } else {
if (TOP_LEFT.equals(currentFieldName) || TOPLEFT.equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, TOP_LEFT_FIELD)) {
GeoUtils.parseGeoPoint(parser, sparse); GeoUtils.parseGeoPoint(parser, sparse);
top = sparse.getLat(); top = sparse.getLat();
left = sparse.getLon(); left = sparse.getLon();
} else if (BOTTOM_RIGHT.equals(currentFieldName) || BOTTOMRIGHT.equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, BOTTOM_RIGHT_FIELD)) {
GeoUtils.parseGeoPoint(parser, sparse); GeoUtils.parseGeoPoint(parser, sparse);
bottom = sparse.getLat(); bottom = sparse.getLat();
right = sparse.getLon(); right = sparse.getLon();
} else if (TOP_RIGHT.equals(currentFieldName) || TOPRIGHT.equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, TOP_RIGHT_FIELD)) {
GeoUtils.parseGeoPoint(parser, sparse); GeoUtils.parseGeoPoint(parser, sparse);
top = sparse.getLat(); top = sparse.getLat();
right = sparse.getLon(); right = sparse.getLon();
} else if (BOTTOM_LEFT.equals(currentFieldName) || BOTTOMLEFT.equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, BOTTOM_LEFT_FIELD)) {
GeoUtils.parseGeoPoint(parser, sparse); GeoUtils.parseGeoPoint(parser, sparse);
bottom = sparse.getLat(); bottom = sparse.getLat();
left = sparse.getLon(); left = sparse.getLon();
@ -136,20 +122,20 @@ public class GeoBoundingBoxQueryParser implements QueryParser<GeoBoundingBoxQuer
} }
} }
} else if (token.isValue()) { } else if (token.isValue()) {
if ("_name".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else if ("coerce".equals(currentFieldName) || ("normalize".equals(currentFieldName))) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, COERCE_FIELD)) {
coerce = parser.booleanValue(); coerce = parser.booleanValue();
if (coerce) { if (coerce) {
ignoreMalformed = true; ignoreMalformed = true;
} }
} else if ("validation_method".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, VALIDATION_METHOD_FIELD)) {
validationMethod = GeoValidationMethod.fromString(parser.text()); validationMethod = GeoValidationMethod.fromString(parser.text());
} else if ("type".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, TYPE_FIELD)) {
type = parser.text(); type = parser.text();
} else if ("ignore_malformed".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, IGNORE_MALFORMED_FIELD)) {
ignoreMalformed = parser.booleanValue(); ignoreMalformed = parser.booleanValue();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "failed to parse [{}] query. unexpected field [{}]", NAME, currentFieldName); throw new ParsingException(parser.getTokenLocation(), "failed to parse [{}] query. unexpected field [{}]", NAME, currentFieldName);

View File

@ -239,21 +239,21 @@ public class GeoDistanceQueryBuilder extends AbstractQueryBuilder<GeoDistanceQue
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.startArray(fieldName).value(center.lon()).value(center.lat()).endArray(); builder.startArray(fieldName).value(center.lon()).value(center.lat()).endArray();
builder.field("distance", distance); builder.field(GeoDistanceQueryParser.DISTANCE_FIELD.getPreferredName(), distance);
builder.field("distance_type", geoDistance.name().toLowerCase(Locale.ROOT)); builder.field(GeoDistanceQueryParser.DISTANCE_TYPE_FIELD.getPreferredName(), geoDistance.name().toLowerCase(Locale.ROOT));
builder.field("optimize_bbox", optimizeBbox); builder.field(GeoDistanceQueryParser.OPTIMIZE_BBOX_FIELD.getPreferredName(), optimizeBbox);
builder.field("validation_method", validationMethod); builder.field(GeoDistanceQueryParser.VALIDATION_METHOD_FIELD.getPreferredName(), validationMethod);
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
builder.endObject(); builder.endObject();
} }
@Override @Override
public int doHashCode() { protected int doHashCode() {
return Objects.hash(center, geoDistance, optimizeBbox, distance, validationMethod); return Objects.hash(center, geoDistance, optimizeBbox, distance, validationMethod);
} }
@Override @Override
public boolean doEquals(GeoDistanceQueryBuilder other) { protected boolean doEquals(GeoDistanceQueryBuilder other) {
return Objects.equals(fieldName, other.fieldName) && return Objects.equals(fieldName, other.fieldName) &&
(distance == other.distance) && (distance == other.distance) &&
Objects.equals(validationMethod, other.validationMethod) && Objects.equals(validationMethod, other.validationMethod) &&

View File

@ -19,6 +19,7 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.geo.GeoDistance; import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.common.geo.GeoPoint; import org.elasticsearch.common.geo.GeoPoint;
@ -41,6 +42,14 @@ import java.io.IOException;
*/ */
public class GeoDistanceQueryParser implements QueryParser<GeoDistanceQueryBuilder> { public class GeoDistanceQueryParser implements QueryParser<GeoDistanceQueryBuilder> {
public static final ParseField VALIDATION_METHOD_FIELD = new ParseField("validation_method");
public static final ParseField IGNORE_MALFORMED_FIELD = new ParseField("ignore_malformed");
public static final ParseField COERCE_FIELD = new ParseField("coerce", "normalize");
public static final ParseField OPTIMIZE_BBOX_FIELD = new ParseField("optimize_bbox");
public static final ParseField DISTANCE_TYPE_FIELD = new ParseField("distance_type");
public static final ParseField UNIT_FIELD = new ParseField("unit");
public static final ParseField DISTANCE_FIELD = new ParseField("distance");
@Override @Override
public String[] names() { public String[] names() {
return new String[]{GeoDistanceQueryBuilder.NAME, "geoDistance"}; return new String[]{GeoDistanceQueryBuilder.NAME, "geoDistance"};
@ -95,15 +104,15 @@ public class GeoDistanceQueryParser implements QueryParser<GeoDistanceQueryBuild
} }
} }
} else if (token.isValue()) { } else if (token.isValue()) {
if ("distance".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, DISTANCE_FIELD)) {
if (token == XContentParser.Token.VALUE_STRING) { if (token == XContentParser.Token.VALUE_STRING) {
vDistance = parser.text(); // a String vDistance = parser.text(); // a String
} else { } else {
vDistance = parser.numberValue(); // a Number vDistance = parser.numberValue(); // a Number
} }
} else if ("unit".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, UNIT_FIELD)) {
unit = DistanceUnit.fromString(parser.text()); unit = DistanceUnit.fromString(parser.text());
} else if ("distance_type".equals(currentFieldName) || "distanceType".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, DISTANCE_TYPE_FIELD)) {
geoDistance = GeoDistance.fromString(parser.text()); geoDistance = GeoDistance.fromString(parser.text());
} else if (currentFieldName.endsWith(GeoPointFieldMapper.Names.LAT_SUFFIX)) { } else if (currentFieldName.endsWith(GeoPointFieldMapper.Names.LAT_SUFFIX)) {
point.resetLat(parser.doubleValue()); point.resetLat(parser.doubleValue());
@ -114,20 +123,20 @@ public class GeoDistanceQueryParser implements QueryParser<GeoDistanceQueryBuild
} else if (currentFieldName.endsWith(GeoPointFieldMapper.Names.GEOHASH_SUFFIX)) { } else if (currentFieldName.endsWith(GeoPointFieldMapper.Names.GEOHASH_SUFFIX)) {
point.resetFromGeoHash(parser.text()); point.resetFromGeoHash(parser.text());
fieldName = currentFieldName.substring(0, currentFieldName.length() - GeoPointFieldMapper.Names.GEOHASH_SUFFIX.length()); fieldName = currentFieldName.substring(0, currentFieldName.length() - GeoPointFieldMapper.Names.GEOHASH_SUFFIX.length());
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else if ("optimize_bbox".equals(currentFieldName) || "optimizeBbox".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, OPTIMIZE_BBOX_FIELD)) {
optimizeBbox = parser.textOrNull(); optimizeBbox = parser.textOrNull();
} else if ("coerce".equals(currentFieldName) || ("normalize".equals(currentFieldName))) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, COERCE_FIELD)) {
coerce = parser.booleanValue(); coerce = parser.booleanValue();
if (coerce == true) { if (coerce == true) {
ignoreMalformed = true; ignoreMalformed = true;
} }
} else if ("ignore_malformed".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, IGNORE_MALFORMED_FIELD)) {
ignoreMalformed = parser.booleanValue(); ignoreMalformed = parser.booleanValue();
} else if ("validation_method".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, VALIDATION_METHOD_FIELD)) {
validationMethod = GeoValidationMethod.fromString(parser.text()); validationMethod = GeoValidationMethod.fromString(parser.text());
} else { } else {
if (fieldName == null) { if (fieldName == null) {

View File

@ -185,12 +185,12 @@ public class HasChildQueryBuilder extends AbstractQueryBuilder<HasChildQueryBuil
@Override @Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.field("query"); builder.field(HasChildQueryParser.QUERY_FIELD.getPreferredName());
query.toXContent(builder, params); query.toXContent(builder, params);
builder.field("child_type", type); builder.field(HasChildQueryParser.TYPE_FIELD.getPreferredName(), type);
builder.field("score_mode", scoreMode.name().toLowerCase(Locale.ROOT)); builder.field(HasChildQueryParser.SCORE_MODE_FIELD.getPreferredName(), scoreMode.name().toLowerCase(Locale.ROOT));
builder.field("min_children", minChildren); builder.field(HasChildQueryParser.MIN_CHILDREN_FIELD.getPreferredName(), minChildren);
builder.field("max_children", maxChildren); builder.field(HasChildQueryParser.MAX_CHILDREN_FIELD.getPreferredName(), maxChildren);
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
if (queryInnerHits != null) { if (queryInnerHits != null) {
queryInnerHits.toXContent(builder, params); queryInnerHits.toXContent(builder, params);

View File

@ -33,7 +33,12 @@ import java.io.IOException;
*/ */
public class HasChildQueryParser implements QueryParser<HasChildQueryBuilder> { public class HasChildQueryParser implements QueryParser<HasChildQueryBuilder> {
private static final ParseField QUERY_FIELD = new ParseField("query", "filter"); public static final ParseField QUERY_FIELD = new ParseField("query", "filter");
public static final ParseField TYPE_FIELD = new ParseField("type", "child_type");
public static final ParseField MAX_CHILDREN_FIELD = new ParseField("max_children");
public static final ParseField MIN_CHILDREN_FIELD = new ParseField("min_children");
public static final ParseField SCORE_MODE_FIELD = new ParseField("score_mode");
public static final ParseField INNER_HITS_FIELD = new ParseField("inner_hits");
@Override @Override
public String[] names() { public String[] names() {
@ -61,23 +66,23 @@ public class HasChildQueryParser implements QueryParser<HasChildQueryBuilder> {
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
if (parseContext.parseFieldMatcher().match(currentFieldName, QUERY_FIELD)) { if (parseContext.parseFieldMatcher().match(currentFieldName, QUERY_FIELD)) {
iqb = parseContext.parseInnerQueryBuilder(); iqb = parseContext.parseInnerQueryBuilder();
} else if ("inner_hits".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, INNER_HITS_FIELD)) {
queryInnerHits = new QueryInnerHits(parser); queryInnerHits = new QueryInnerHits(parser);
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[has_child] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[has_child] query does not support [" + currentFieldName + "]");
} }
} else if (token.isValue()) { } else if (token.isValue()) {
if ("type".equals(currentFieldName) || "child_type".equals(currentFieldName) || "childType".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, TYPE_FIELD)) {
childType = parser.text(); childType = parser.text();
} else if ("score_mode".equals(currentFieldName) || "scoreMode".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, SCORE_MODE_FIELD)) {
scoreMode = parseScoreMode(parser.text()); scoreMode = parseScoreMode(parser.text());
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else if ("min_children".equals(currentFieldName) || "minChildren".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, MIN_CHILDREN_FIELD)) {
minChildren = parser.intValue(true); minChildren = parser.intValue(true);
} else if ("max_children".equals(currentFieldName) || "maxChildren".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, MAX_CHILDREN_FIELD)) {
maxChildren = parser.intValue(true); maxChildren = parser.intValue(true);
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[has_child] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[has_child] query does not support [" + currentFieldName + "]");

View File

@ -199,10 +199,10 @@ public class HasParentQueryBuilder extends AbstractQueryBuilder<HasParentQueryBu
@Override @Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.field("query"); builder.field(HasParentQueryParser.QUERY_FIELD.getPreferredName());
query.toXContent(builder, params); query.toXContent(builder, params);
builder.field("parent_type", type); builder.field(HasParentQueryParser.TYPE_FIELD.getPreferredName(), type);
builder.field("score", score); builder.field(HasParentQueryParser.SCORE_FIELD.getPreferredName(), score);
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
if (innerHit != null) { if (innerHit != null) {
innerHit.toXContent(builder, params); innerHit.toXContent(builder, params);

View File

@ -30,9 +30,11 @@ import java.io.IOException;
public class HasParentQueryParser implements QueryParser<HasParentQueryBuilder> { public class HasParentQueryParser implements QueryParser<HasParentQueryBuilder> {
private static final HasParentQueryBuilder PROTOTYPE = new HasParentQueryBuilder("", EmptyQueryBuilder.PROTOTYPE); private static final HasParentQueryBuilder PROTOTYPE = new HasParentQueryBuilder("", EmptyQueryBuilder.PROTOTYPE);
private static final ParseField QUERY_FIELD = new ParseField("query", "filter"); public static final ParseField QUERY_FIELD = new ParseField("query", "filter");
private static final ParseField SCORE_FIELD = new ParseField("score_mode").withAllDeprecated("score"); //public static final ParseField SCORE_MODE_FIELD = new ParseField("score_mode").withAllDeprecated("score");
private static final ParseField TYPE_FIELD = new ParseField("parent_type", "type"); public static final ParseField SCORE_MODE_FIELD = new ParseField("score_mode").withAllDeprecated("score");
public static final ParseField TYPE_FIELD = new ParseField("parent_type", "type");
public static final ParseField SCORE_FIELD = new ParseField("score");
@Override @Override
public String[] names() { public String[] names() {
@ -42,7 +44,6 @@ public class HasParentQueryParser implements QueryParser<HasParentQueryBuilder>
@Override @Override
public HasParentQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException { public HasParentQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
float boost = AbstractQueryBuilder.DEFAULT_BOOST; float boost = AbstractQueryBuilder.DEFAULT_BOOST;
String parentType = null; String parentType = null;
boolean score = HasParentQueryBuilder.DEFAULT_SCORE; boolean score = HasParentQueryBuilder.DEFAULT_SCORE;
@ -66,7 +67,7 @@ public class HasParentQueryParser implements QueryParser<HasParentQueryBuilder>
} else if (token.isValue()) { } else if (token.isValue()) {
if (parseContext.parseFieldMatcher().match(currentFieldName, TYPE_FIELD)) { if (parseContext.parseFieldMatcher().match(currentFieldName, TYPE_FIELD)) {
parentType = parser.text(); parentType = parser.text();
} else if (parseContext.parseFieldMatcher().match(currentFieldName, SCORE_FIELD)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, SCORE_MODE_FIELD)) {
String scoreModeValue = parser.text(); String scoreModeValue = parser.text();
if ("score".equals(scoreModeValue)) { if ("score".equals(scoreModeValue)) {
score = true; score = true;
@ -75,11 +76,11 @@ public class HasParentQueryParser implements QueryParser<HasParentQueryBuilder>
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[has_parent] query does not support [" + scoreModeValue + "] as an option for score_mode"); throw new ParsingException(parser.getTokenLocation(), "[has_parent] query does not support [" + scoreModeValue + "] as an option for score_mode");
} }
} else if ("score".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, SCORE_FIELD)) {
score = parser.booleanValue(); score = parser.booleanValue();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[has_parent] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[has_parent] query does not support [" + currentFieldName + "]");

View File

@ -90,8 +90,8 @@ public class IdsQueryBuilder extends AbstractQueryBuilder<IdsQueryBuilder> {
@Override @Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.array("types", types); builder.array(IdsQueryParser.TYPE_FIELD.getPreferredName(), types);
builder.startArray("values"); builder.startArray(IdsQueryParser.VALUES_FIELD.getPreferredName());
for (String value : ids) { for (String value : ids) {
builder.value(value); builder.value(value);
} }

View File

@ -19,6 +19,7 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
@ -32,6 +33,10 @@ import java.util.List;
*/ */
public class IdsQueryParser implements QueryParser<IdsQueryBuilder> { public class IdsQueryParser implements QueryParser<IdsQueryBuilder> {
public static final ParseField TYPE_FIELD = new ParseField("type", "types", "_type");
public static final ParseField VALUES_FIELD = new ParseField("values");
@Override @Override
public String[] names() { public String[] names() {
return new String[]{IdsQueryBuilder.NAME}; return new String[]{IdsQueryBuilder.NAME};
@ -55,7 +60,7 @@ public class IdsQueryParser implements QueryParser<IdsQueryBuilder> {
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_ARRAY) { } else if (token == XContentParser.Token.START_ARRAY) {
if ("values".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, VALUES_FIELD)) {
idsProvided = true; idsProvided = true;
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
if ((token == XContentParser.Token.VALUE_STRING) || if ((token == XContentParser.Token.VALUE_STRING) ||
@ -70,7 +75,7 @@ public class IdsQueryParser implements QueryParser<IdsQueryBuilder> {
+ token); + token);
} }
} }
} else if ("types".equals(currentFieldName) || "type".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, TYPE_FIELD)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
String value = parser.textOrNull(); String value = parser.textOrNull();
if (value == null) { if (value == null) {
@ -82,11 +87,11 @@ public class IdsQueryParser implements QueryParser<IdsQueryBuilder> {
throw new ParsingException(parser.getTokenLocation(), "[" + IdsQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[" + IdsQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]");
} }
} else if (token.isValue()) { } else if (token.isValue()) {
if ("type".equals(currentFieldName) || "_type".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, TYPE_FIELD)) {
types = Collections.singletonList(parser.text()); types = Collections.singletonList(parser.text());
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[" + IdsQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[" + IdsQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]");

View File

@ -93,10 +93,10 @@ public class IndicesQueryBuilder extends AbstractQueryBuilder<IndicesQueryBuilde
@Override @Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.field("indices", indices); builder.field(IndicesQueryParser.INDICES_FIELD.getPreferredName(), indices);
builder.field("query"); builder.field(IndicesQueryParser.QUERY_FIELD.getPreferredName());
innerQuery.toXContent(builder, params); innerQuery.toXContent(builder, params);
builder.field("no_match_query"); builder.field(IndicesQueryParser.NO_MATCH_QUERY.getPreferredName());
noMatchQuery.toXContent(builder, params); noMatchQuery.toXContent(builder, params);
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
builder.endObject(); builder.endObject();

View File

@ -32,8 +32,11 @@ import java.util.Collection;
*/ */
public class IndicesQueryParser implements QueryParser { public class IndicesQueryParser implements QueryParser {
private static final ParseField QUERY_FIELD = new ParseField("query"); public static final ParseField QUERY_FIELD = new ParseField("query");
private static final ParseField NO_MATCH_QUERY = new ParseField("no_match_query"); public static final ParseField NO_MATCH_QUERY = new ParseField("no_match_query");
public static final ParseField INDEX_FIELD = new ParseField("index");
public static final ParseField INDICES_FIELD = new ParseField("indices");
@Override @Override
public String[] names() { public String[] names() {
@ -65,7 +68,7 @@ public class IndicesQueryParser implements QueryParser {
throw new ParsingException(parser.getTokenLocation(), "[indices] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[indices] query does not support [" + currentFieldName + "]");
} }
} else if (token == XContentParser.Token.START_ARRAY) { } else if (token == XContentParser.Token.START_ARRAY) {
if ("indices".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, INDICES_FIELD)) {
if (indices.isEmpty() == false) { if (indices.isEmpty() == false) {
throw new ParsingException(parser.getTokenLocation(), "[indices] indices or index already specified"); throw new ParsingException(parser.getTokenLocation(), "[indices] indices or index already specified");
} }
@ -80,16 +83,16 @@ public class IndicesQueryParser implements QueryParser {
throw new ParsingException(parser.getTokenLocation(), "[indices] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[indices] query does not support [" + currentFieldName + "]");
} }
} else if (token.isValue()) { } else if (token.isValue()) {
if ("index".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, INDEX_FIELD)) {
if (indices.isEmpty() == false) { if (indices.isEmpty() == false) {
throw new ParsingException(parser.getTokenLocation(), "[indices] indices or index already specified"); throw new ParsingException(parser.getTokenLocation(), "[indices] indices or index already specified");
} }
indices.add(parser.text()); indices.add(parser.text());
} else if (parseContext.parseFieldMatcher().match(currentFieldName, NO_MATCH_QUERY)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, NO_MATCH_QUERY)) {
noMatchQuery = parseNoMatchQuery(parser.text()); noMatchQuery = parseNoMatchQuery(parser.text());
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[indices] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[indices] query does not support [" + currentFieldName + "]");

View File

@ -47,9 +47,9 @@ public class MatchAllQueryParser implements QueryParser<MatchAllQueryBuilder> {
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token.isValue()) { } else if (token.isValue()) {
if ("_name".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[" + MatchAllQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[" + MatchAllQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]");

View File

@ -44,9 +44,9 @@ public class MatchNoneQueryParser implements QueryParser<MatchNoneQueryBuilder>
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token.isValue()) { } else if (token.isValue()) {
if ("_name".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "["+MatchNoneQueryBuilder.NAME+"] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "["+MatchNoneQueryBuilder.NAME+"] query does not support [" + currentFieldName + "]");

View File

@ -129,6 +129,11 @@ public class MatchQueryBuilder extends AbstractQueryBuilder<MatchQueryBuilder> {
return this; return this;
} }
/** Returns the operator to use in a boolean query.*/
public Operator operator() {
return this.operator;
}
/** /**
* Explicitly set the analyzer to use. Defaults to use explicit mapping config for the field, or, if not * Explicitly set the analyzer to use. Defaults to use explicit mapping config for the field, or, if not
* set, the default search analyzer. * set, the default search analyzer.
@ -312,30 +317,30 @@ public class MatchQueryBuilder extends AbstractQueryBuilder<MatchQueryBuilder> {
builder.startObject(NAME); builder.startObject(NAME);
builder.startObject(fieldName); builder.startObject(fieldName);
builder.field("query", value); builder.field(MatchQueryParser.QUERY_FIELD.getPreferredName(), value);
builder.field("type", type.toString().toLowerCase(Locale.ENGLISH)); builder.field(MatchQueryParser.TYPE_FIELD.getPreferredName(), type.toString().toLowerCase(Locale.ENGLISH));
builder.field("operator", operator.toString()); builder.field(MatchQueryParser.OPERATOR_FIELD.getPreferredName(), operator.toString());
if (analyzer != null) { if (analyzer != null) {
builder.field("analyzer", analyzer); builder.field(MatchQueryParser.ANALYZER_FIELD.getPreferredName(), analyzer);
} }
builder.field("slop", slop); builder.field(MatchQueryParser.SLOP_FIELD.getPreferredName(), slop);
if (fuzziness != null) { if (fuzziness != null) {
fuzziness.toXContent(builder, params); fuzziness.toXContent(builder, params);
} }
builder.field("prefix_length", prefixLength); builder.field(MatchQueryParser.PREFIX_LENGTH_FIELD.getPreferredName(), prefixLength);
builder.field("max_expansions", maxExpansions); builder.field(MatchQueryParser.MAX_EXPANSIONS_FIELD.getPreferredName(), maxExpansions);
if (minimumShouldMatch != null) { if (minimumShouldMatch != null) {
builder.field("minimum_should_match", minimumShouldMatch); builder.field(MatchQueryParser.MINIMUM_SHOULD_MATCH_FIELD.getPreferredName(), minimumShouldMatch);
} }
if (fuzzyRewrite != null) { if (fuzzyRewrite != null) {
builder.field("fuzzy_rewrite", fuzzyRewrite); builder.field(MatchQueryParser.FUZZY_REWRITE_FIELD.getPreferredName(), fuzzyRewrite);
} }
// LUCENE 4 UPGRADE we need to document this & test this // LUCENE 4 UPGRADE we need to document this & test this
builder.field("fuzzy_transpositions", fuzzyTranspositions); builder.field(MatchQueryParser.FUZZY_TRANSPOSITIONS_FIELD.getPreferredName(), fuzzyTranspositions);
builder.field("lenient", lenient); builder.field(MatchQueryParser.LENIENT_FIELD.getPreferredName(), lenient);
builder.field("zero_terms_query", zeroTermsQuery.toString()); builder.field(MatchQueryParser.ZERO_TERMS_QUERY_FIELD.getPreferredName(), zeroTermsQuery.toString());
if (cutoffFrequency != null) { if (cutoffFrequency != null) {
builder.field("cutoff_frequency", cutoffFrequency); builder.field(MatchQueryParser.CUTOFF_FREQUENCY_FIELD.getPreferredName(), cutoffFrequency);
} }
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
builder.endObject(); builder.endObject();

View File

@ -20,6 +20,7 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.apache.lucene.search.FuzzyQuery; import org.apache.lucene.search.FuzzyQuery;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.unit.Fuzziness; import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
@ -33,6 +34,22 @@ import java.io.IOException;
*/ */
public class MatchQueryParser implements QueryParser<MatchQueryBuilder> { public class MatchQueryParser implements QueryParser<MatchQueryBuilder> {
public static final ParseField MATCH_PHRASE_FIELD = new ParseField("match_phrase", "text_phrase");
public static final ParseField MATCH_PHRASE_PREFIX_FIELD = new ParseField("match_phrase_prefix", "text_phrase_prefix");
public static final ParseField SLOP_FIELD = new ParseField("slop", "phrase_slop");
public static final ParseField ZERO_TERMS_QUERY_FIELD = new ParseField("zero_terms_query");
public static final ParseField CUTOFF_FREQUENCY_FIELD = new ParseField("cutoff_frequency");
public static final ParseField LENIENT_FIELD = new ParseField("lenient");
public static final ParseField FUZZY_TRANSPOSITIONS_FIELD = new ParseField("fuzzy_transpositions");
public static final ParseField FUZZY_REWRITE_FIELD = new ParseField("fuzzy_rewrite");
public static final ParseField MINIMUM_SHOULD_MATCH_FIELD = new ParseField("minimum_should_match");
public static final ParseField OPERATOR_FIELD = new ParseField("operator");
public static final ParseField MAX_EXPANSIONS_FIELD = new ParseField("max_expansions");
public static final ParseField PREFIX_LENGTH_FIELD = new ParseField("prefix_length");
public static final ParseField ANALYZER_FIELD = new ParseField("analyzer");
public static final ParseField TYPE_FIELD = new ParseField("type");
public static final ParseField QUERY_FIELD = new ParseField("query");
@Override @Override
public String[] names() { public String[] names() {
return new String[]{ return new String[]{
@ -45,11 +62,9 @@ public class MatchQueryParser implements QueryParser<MatchQueryBuilder> {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
MatchQuery.Type type = MatchQuery.Type.BOOLEAN; MatchQuery.Type type = MatchQuery.Type.BOOLEAN;
if ("match_phrase".equals(parser.currentName()) || "matchPhrase".equals(parser.currentName()) || if (parseContext.parseFieldMatcher().match(parser.currentName(), MATCH_PHRASE_FIELD)) {
"text_phrase".equals(parser.currentName()) || "textPhrase".equals(parser.currentName())) {
type = MatchQuery.Type.PHRASE; type = MatchQuery.Type.PHRASE;
} else if ("match_phrase_prefix".equals(parser.currentName()) || "matchPhrasePrefix".equals(parser.currentName()) || } else if (parseContext.parseFieldMatcher().match(parser.currentName(), MATCH_PHRASE_PREFIX_FIELD)) {
"text_phrase_prefix".equals(parser.currentName()) || "textPhrasePrefix".equals(parser.currentName())) {
type = MatchQuery.Type.PHRASE_PREFIX; type = MatchQuery.Type.PHRASE_PREFIX;
} }
@ -82,44 +97,44 @@ public class MatchQueryParser implements QueryParser<MatchQueryBuilder> {
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token.isValue()) { } else if (token.isValue()) {
if ("query".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, QUERY_FIELD)) {
value = parser.objectText(); value = parser.objectText();
} else if ("type".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, TYPE_FIELD)) {
String tStr = parser.text(); String tStr = parser.text();
if ("boolean".equals(tStr)) { if ("boolean".equals(tStr)) {
type = MatchQuery.Type.BOOLEAN; type = MatchQuery.Type.BOOLEAN;
} else if ("phrase".equals(tStr)) { } else if ("phrase".equals(tStr)) {
type = MatchQuery.Type.PHRASE; type = MatchQuery.Type.PHRASE;
} else if ("phrase_prefix".equals(tStr) || "phrasePrefix".equals(currentFieldName)) { } else if ("phrase_prefix".equals(tStr) || ("phrasePrefix".equals(tStr))) {
type = MatchQuery.Type.PHRASE_PREFIX; type = MatchQuery.Type.PHRASE_PREFIX;
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[" + MatchQueryBuilder.NAME + "] query does not support type " + tStr); throw new ParsingException(parser.getTokenLocation(), "[" + MatchQueryBuilder.NAME + "] query does not support type " + tStr);
} }
} else if ("analyzer".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, ANALYZER_FIELD)) {
analyzer = parser.text(); analyzer = parser.text();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else if ("slop".equals(currentFieldName) || "phrase_slop".equals(currentFieldName) || "phraseSlop".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, SLOP_FIELD)) {
slop = parser.intValue(); slop = parser.intValue();
} else if (parseContext.parseFieldMatcher().match(currentFieldName, Fuzziness.FIELD)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, Fuzziness.FIELD)) {
fuzziness = Fuzziness.parse(parser); fuzziness = Fuzziness.parse(parser);
} else if ("prefix_length".equals(currentFieldName) || "prefixLength".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, PREFIX_LENGTH_FIELD)) {
prefixLength = parser.intValue(); prefixLength = parser.intValue();
} else if ("max_expansions".equals(currentFieldName) || "maxExpansions".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, MAX_EXPANSIONS_FIELD)) {
maxExpansion = parser.intValue(); maxExpansion = parser.intValue();
} else if ("operator".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, OPERATOR_FIELD)) {
operator = Operator.fromString(parser.text()); operator = Operator.fromString(parser.text());
} else if ("minimum_should_match".equals(currentFieldName) || "minimumShouldMatch".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, MINIMUM_SHOULD_MATCH_FIELD)) {
minimumShouldMatch = parser.textOrNull(); minimumShouldMatch = parser.textOrNull();
} else if ("fuzzy_rewrite".equals(currentFieldName) || "fuzzyRewrite".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, FUZZY_REWRITE_FIELD)) {
fuzzyRewrite = parser.textOrNull(); fuzzyRewrite = parser.textOrNull();
} else if ("fuzzy_transpositions".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, FUZZY_TRANSPOSITIONS_FIELD)) {
fuzzyTranspositions = parser.booleanValue(); fuzzyTranspositions = parser.booleanValue();
} else if ("lenient".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, LENIENT_FIELD)) {
lenient = parser.booleanValue(); lenient = parser.booleanValue();
} else if ("cutoff_frequency".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, CUTOFF_FREQUENCY_FIELD)) {
cutOffFrequency = parser.floatValue(); cutOffFrequency = parser.floatValue();
} else if ("zero_terms_query".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, ZERO_TERMS_QUERY_FIELD)) {
String zeroTermsDocs = parser.text(); String zeroTermsDocs = parser.text();
if ("none".equalsIgnoreCase(zeroTermsDocs)) { if ("none".equalsIgnoreCase(zeroTermsDocs)) {
zeroTermsQuery = MatchQuery.ZeroTermsQuery.NONE; zeroTermsQuery = MatchQuery.ZeroTermsQuery.NONE;
@ -128,7 +143,7 @@ public class MatchQueryParser implements QueryParser<MatchQueryBuilder> {
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "Unsupported zero_terms_docs value [" + zeroTermsDocs + "]"); throw new ParsingException(parser.getTokenLocation(), "Unsupported zero_terms_docs value [" + zeroTermsDocs + "]");
} }
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[" + MatchQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[" + MatchQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]");

View File

@ -104,9 +104,9 @@ public class MissingQueryBuilder extends AbstractQueryBuilder<MissingQueryBuilde
@Override @Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.field("field", fieldPattern); builder.field(MissingQueryParser.FIELD_FIELD.getPreferredName(), fieldPattern);
builder.field("null_value", nullValue); builder.field(MissingQueryParser.NULL_VALUE_FIELD.getPreferredName(), nullValue);
builder.field("existence", existence); builder.field(MissingQueryParser.EXISTENCE_FIELD.getPreferredName(), existence);
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
builder.endObject(); builder.endObject();
} }

View File

@ -19,6 +19,7 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
@ -29,6 +30,10 @@ import java.io.IOException;
*/ */
public class MissingQueryParser implements QueryParser<MissingQueryBuilder> { public class MissingQueryParser implements QueryParser<MissingQueryBuilder> {
public static final ParseField FIELD_FIELD = new ParseField("field");
public static final ParseField NULL_VALUE_FIELD = new ParseField("null_value");
public static final ParseField EXISTENCE_FIELD = new ParseField("existence");
@Override @Override
public String[] names() { public String[] names() {
return new String[]{MissingQueryBuilder.NAME}; return new String[]{MissingQueryBuilder.NAME};
@ -50,15 +55,15 @@ public class MissingQueryParser implements QueryParser<MissingQueryBuilder> {
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token.isValue()) { } else if (token.isValue()) {
if ("field".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, FIELD_FIELD)) {
fieldPattern = parser.text(); fieldPattern = parser.text();
} else if ("null_value".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, NULL_VALUE_FIELD)) {
nullValue = parser.booleanValue(); nullValue = parser.booleanValue();
} else if ("existence".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, EXISTENCE_FIELD)) {
existence = parser.booleanValue(); existence = parser.booleanValue();
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[" + MissingQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[" + MissingQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]");

View File

@ -457,40 +457,40 @@ public class MultiMatchQueryBuilder extends AbstractQueryBuilder<MultiMatchQuery
@Override @Override
public void doXContent(XContentBuilder builder, Params params) throws IOException { public void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.field("query", value); builder.field(MultiMatchQueryParser.QUERY_FIELD.getPreferredName(), value);
builder.startArray("fields"); builder.startArray(MultiMatchQueryParser.FIELDS_FIELD.getPreferredName());
for (Map.Entry<String, Float> fieldEntry : this.fieldsBoosts.entrySet()) { for (Map.Entry<String, Float> fieldEntry : this.fieldsBoosts.entrySet()) {
builder.value(fieldEntry.getKey() + "^" + fieldEntry.getValue()); builder.value(fieldEntry.getKey() + "^" + fieldEntry.getValue());
} }
builder.endArray(); builder.endArray();
builder.field("type", type.toString().toLowerCase(Locale.ENGLISH)); builder.field(MultiMatchQueryParser.TYPE_FIELD.getPreferredName(), type.toString().toLowerCase(Locale.ENGLISH));
builder.field("operator", operator.toString()); builder.field(MultiMatchQueryParser.OPERATOR_FIELD.getPreferredName(), operator.toString());
if (analyzer != null) { if (analyzer != null) {
builder.field("analyzer", analyzer); builder.field(MultiMatchQueryParser.ANALYZER_FIELD.getPreferredName(), analyzer);
} }
builder.field("slop", slop); builder.field(MultiMatchQueryParser.SLOP_FIELD.getPreferredName(), slop);
if (fuzziness != null) { if (fuzziness != null) {
fuzziness.toXContent(builder, params); fuzziness.toXContent(builder, params);
} }
builder.field("prefix_length", prefixLength); builder.field(MultiMatchQueryParser.PREFIX_LENGTH_FIELD.getPreferredName(), prefixLength);
builder.field("max_expansions", maxExpansions); builder.field(MultiMatchQueryParser.MAX_EXPANSIONS_FIELD.getPreferredName(), maxExpansions);
if (minimumShouldMatch != null) { if (minimumShouldMatch != null) {
builder.field("minimum_should_match", minimumShouldMatch); builder.field(MultiMatchQueryParser.MINIMUM_SHOULD_MATCH_FIELD.getPreferredName(), minimumShouldMatch);
} }
if (fuzzyRewrite != null) { if (fuzzyRewrite != null) {
builder.field("fuzzy_rewrite", fuzzyRewrite); builder.field(MultiMatchQueryParser.FUZZY_REWRITE_FIELD.getPreferredName(), fuzzyRewrite);
} }
if (useDisMax != null) { if (useDisMax != null) {
builder.field("use_dis_max", useDisMax); builder.field(MultiMatchQueryParser.USE_DIS_MAX_FIELD.getPreferredName(), useDisMax);
} }
if (tieBreaker != null) { if (tieBreaker != null) {
builder.field("tie_breaker", tieBreaker); builder.field(MultiMatchQueryParser.TIE_BREAKER_FIELD.getPreferredName(), tieBreaker);
} }
builder.field("lenient", lenient); builder.field(MultiMatchQueryParser.LENIENT_FIELD.getPreferredName(), lenient);
if (cutoffFrequency != null) { if (cutoffFrequency != null) {
builder.field("cutoff_frequency", cutoffFrequency); builder.field(MultiMatchQueryParser.CUTOFF_FREQUENCY_FIELD.getPreferredName(), cutoffFrequency);
} }
builder.field("zero_terms_query", zeroTermsQuery.toString()); builder.field(MultiMatchQueryParser.ZERO_TERMS_QUERY_FIELD.getPreferredName(), zeroTermsQuery.toString());
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
builder.endObject(); builder.endObject();
} }

View File

@ -19,9 +19,11 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.unit.Fuzziness; import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.MoreLikeThisQueryParser.Field;
import org.elasticsearch.index.search.MatchQuery; import org.elasticsearch.index.search.MatchQuery;
import java.io.IOException; import java.io.IOException;
@ -33,6 +35,22 @@ import java.util.Map;
*/ */
public class MultiMatchQueryParser implements QueryParser<MultiMatchQueryBuilder> { public class MultiMatchQueryParser implements QueryParser<MultiMatchQueryBuilder> {
public static final ParseField SLOP_FIELD = new ParseField("slop", "phrase_slop");
public static final ParseField ZERO_TERMS_QUERY_FIELD = new ParseField("zero_terms_query");
public static final ParseField LENIENT_FIELD = new ParseField("lenient");
public static final ParseField CUTOFF_FREQUENCY_FIELD = new ParseField("cutoff_frequency");
public static final ParseField TIE_BREAKER_FIELD = new ParseField("tie_breaker");
public static final ParseField USE_DIS_MAX_FIELD = new ParseField("use_dis_max");
public static final ParseField FUZZY_REWRITE_FIELD = new ParseField("fuzzy_rewrite");
public static final ParseField MINIMUM_SHOULD_MATCH_FIELD = new ParseField("minimum_should_match");
public static final ParseField OPERATOR_FIELD = new ParseField("operator");
public static final ParseField MAX_EXPANSIONS_FIELD = new ParseField("max_expansions");
public static final ParseField PREFIX_LENGTH_FIELD = new ParseField("prefix_length");
public static final ParseField ANALYZER_FIELD = new ParseField("analyzer");
public static final ParseField TYPE_FIELD = new ParseField("type");
public static final ParseField QUERY_FIELD = new ParseField("query");
public static final ParseField FIELDS_FIELD = new ParseField("fields");
@Override @Override
public String[] names() { public String[] names() {
return new String[]{ return new String[]{
@ -69,7 +87,7 @@ public class MultiMatchQueryParser implements QueryParser<MultiMatchQueryBuilder
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if ("fields".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, FIELDS_FIELD)) {
if (token == XContentParser.Token.START_ARRAY) { if (token == XContentParser.Token.START_ARRAY) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
parseFieldAndBoost(parser, fieldsBoosts); parseFieldAndBoost(parser, fieldsBoosts);
@ -80,37 +98,37 @@ public class MultiMatchQueryParser implements QueryParser<MultiMatchQueryBuilder
throw new ParsingException(parser.getTokenLocation(), "[" + MultiMatchQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[" + MultiMatchQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]");
} }
} else if (token.isValue()) { } else if (token.isValue()) {
if ("query".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, QUERY_FIELD)) {
value = parser.objectText(); value = parser.objectText();
} else if ("type".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, TYPE_FIELD)) {
type = MultiMatchQueryBuilder.Type.parse(parser.text(), parseContext.parseFieldMatcher()); type = MultiMatchQueryBuilder.Type.parse(parser.text(), parseContext.parseFieldMatcher());
} else if ("analyzer".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, ANALYZER_FIELD)) {
analyzer = parser.text(); analyzer = parser.text();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else if ("slop".equals(currentFieldName) || "phrase_slop".equals(currentFieldName) || "phraseSlop".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, SLOP_FIELD)) {
slop = parser.intValue(); slop = parser.intValue();
} else if (parseContext.parseFieldMatcher().match(currentFieldName, Fuzziness.FIELD)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, Fuzziness.FIELD)) {
fuzziness = Fuzziness.parse(parser); fuzziness = Fuzziness.parse(parser);
} else if ("prefix_length".equals(currentFieldName) || "prefixLength".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, PREFIX_LENGTH_FIELD)) {
prefixLength = parser.intValue(); prefixLength = parser.intValue();
} else if ("max_expansions".equals(currentFieldName) || "maxExpansions".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, MAX_EXPANSIONS_FIELD)) {
maxExpansions = parser.intValue(); maxExpansions = parser.intValue();
} else if ("operator".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, OPERATOR_FIELD)) {
operator = Operator.fromString(parser.text()); operator = Operator.fromString(parser.text());
} else if ("minimum_should_match".equals(currentFieldName) || "minimumShouldMatch".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, MINIMUM_SHOULD_MATCH_FIELD)) {
minimumShouldMatch = parser.textOrNull(); minimumShouldMatch = parser.textOrNull();
} else if ("fuzzy_rewrite".equals(currentFieldName) || "fuzzyRewrite".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, FUZZY_REWRITE_FIELD)) {
fuzzyRewrite = parser.textOrNull(); fuzzyRewrite = parser.textOrNull();
} else if ("use_dis_max".equals(currentFieldName) || "useDisMax".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, USE_DIS_MAX_FIELD)) {
useDisMax = parser.booleanValue(); useDisMax = parser.booleanValue();
} else if ("tie_breaker".equals(currentFieldName) || "tieBreaker".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, TIE_BREAKER_FIELD)) {
tieBreaker = parser.floatValue(); tieBreaker = parser.floatValue();
} else if ("cutoff_frequency".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, CUTOFF_FREQUENCY_FIELD)) {
cutoffFrequency = parser.floatValue(); cutoffFrequency = parser.floatValue();
} else if ("lenient".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, LENIENT_FIELD)) {
lenient = parser.booleanValue(); lenient = parser.booleanValue();
} else if ("zero_terms_query".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, ZERO_TERMS_QUERY_FIELD)) {
String zeroTermsDocs = parser.text(); String zeroTermsDocs = parser.text();
if ("none".equalsIgnoreCase(zeroTermsDocs)) { if ("none".equalsIgnoreCase(zeroTermsDocs)) {
zeroTermsQuery = MatchQuery.ZeroTermsQuery.NONE; zeroTermsQuery = MatchQuery.ZeroTermsQuery.NONE;
@ -119,7 +137,7 @@ public class MultiMatchQueryParser implements QueryParser<MultiMatchQueryBuilder
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "Unsupported zero_terms_docs value [" + zeroTermsDocs + "]"); throw new ParsingException(parser.getTokenLocation(), "Unsupported zero_terms_docs value [" + zeroTermsDocs + "]");
} }
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[" + MultiMatchQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[" + MultiMatchQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]");

View File

@ -117,11 +117,11 @@ public class NestedQueryBuilder extends AbstractQueryBuilder<NestedQueryBuilder>
@Override @Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.field("query"); builder.field(NestedQueryParser.QUERY_FIELD.getPreferredName());
query.toXContent(builder, params); query.toXContent(builder, params);
builder.field("path", path); builder.field(NestedQueryParser.PATH_FIELD.getPreferredName(), path);
if (scoreMode != null) { if (scoreMode != null) {
builder.field("score_mode", scoreMode.name().toLowerCase(Locale.ROOT)); builder.field(NestedQueryParser.SCORE_MODE_FIELD.getPreferredName(), scoreMode.name().toLowerCase(Locale.ROOT));
} }
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
if (queryInnerHits != null) { if (queryInnerHits != null) {

View File

@ -20,6 +20,7 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.apache.lucene.search.join.ScoreMode; import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
@ -30,6 +31,10 @@ import java.io.IOException;
public class NestedQueryParser implements QueryParser<NestedQueryBuilder> { public class NestedQueryParser implements QueryParser<NestedQueryBuilder> {
private static final NestedQueryBuilder PROTOTYPE = new NestedQueryBuilder("", EmptyQueryBuilder.PROTOTYPE); private static final NestedQueryBuilder PROTOTYPE = new NestedQueryBuilder("", EmptyQueryBuilder.PROTOTYPE);
public static final ParseField SCORE_MODE_FIELD = new ParseField("score_mode");
public static final ParseField PATH_FIELD = new ParseField("path");
public static final ParseField QUERY_FIELD = new ParseField("query");
public static final ParseField INNER_HITS_FIELD = new ParseField("inner_hits");
@Override @Override
public String[] names() { public String[] names() {
@ -51,19 +56,19 @@ public class NestedQueryParser implements QueryParser<NestedQueryBuilder> {
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
if ("query".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, QUERY_FIELD)) {
query = parseContext.parseInnerQueryBuilder(); query = parseContext.parseInnerQueryBuilder();
} else if ("inner_hits".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, INNER_HITS_FIELD)) {
queryInnerHits = new QueryInnerHits(parser); queryInnerHits = new QueryInnerHits(parser);
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[nested] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[nested] query does not support [" + currentFieldName + "]");
} }
} else if (token.isValue()) { } else if (token.isValue()) {
if ("path".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, PATH_FIELD)) {
path = parser.text(); path = parser.text();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else if ("score_mode".equals(currentFieldName) || "scoreMode".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, SCORE_MODE_FIELD)) {
String sScoreMode = parser.text(); String sScoreMode = parser.text();
if ("avg".equals(sScoreMode)) { if ("avg".equals(sScoreMode)) {
scoreMode = ScoreMode.Avg; scoreMode = ScoreMode.Avg;
@ -78,7 +83,7 @@ public class NestedQueryParser implements QueryParser<NestedQueryBuilder> {
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "illegal score_mode for nested query [" + sScoreMode + "]"); throw new ParsingException(parser.getTokenLocation(), "illegal score_mode for nested query [" + sScoreMode + "]");
} }
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[nested] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[nested] query does not support [" + currentFieldName + "]");

View File

@ -87,9 +87,9 @@ public class PrefixQueryBuilder extends AbstractQueryBuilder<PrefixQueryBuilder>
public void doXContent(XContentBuilder builder, Params params) throws IOException { public void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.startObject(fieldName); builder.startObject(fieldName);
builder.field("prefix", this.value); builder.field(PrefixQueryParser.PREFIX_FIELD.getPreferredName(), this.value);
if (rewrite != null) { if (rewrite != null) {
builder.field("rewrite", rewrite); builder.field(PrefixQueryParser.REWRITE_FIELD.getPreferredName(), rewrite);
} }
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
builder.endObject(); builder.endObject();

View File

@ -30,7 +30,8 @@ import java.io.IOException;
*/ */
public class PrefixQueryParser implements QueryParser<PrefixQueryBuilder> { public class PrefixQueryParser implements QueryParser<PrefixQueryBuilder> {
private static final ParseField NAME_FIELD = new ParseField("_name").withAllDeprecated("query name is not supported in short version of prefix query"); public static final ParseField PREFIX_FIELD = new ParseField("value", "prefix");
public static final ParseField REWRITE_FIELD = new ParseField("rewrite");
@Override @Override
public String[] names() { public String[] names() {
@ -60,13 +61,13 @@ public class PrefixQueryParser implements QueryParser<PrefixQueryBuilder> {
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else { } else {
if ("_name".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else if ("value".equals(currentFieldName) || "prefix".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, PREFIX_FIELD)) {
value = parser.textOrNull(); value = parser.textOrNull();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else if ("rewrite".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, REWRITE_FIELD)) {
rewrite = parser.textOrNull(); rewrite = parser.textOrNull();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[regexp] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[regexp] query does not support [" + currentFieldName + "]");
@ -74,12 +75,8 @@ public class PrefixQueryParser implements QueryParser<PrefixQueryBuilder> {
} }
} }
} else { } else {
if (parseContext.parseFieldMatcher().match(currentFieldName, NAME_FIELD)) {
queryName = parser.text();
} else {
fieldName = currentFieldName; fieldName = currentFieldName;
value = parser.textOrNull(); value = parser.textOrNull();
}
} }
} }

View File

@ -468,58 +468,58 @@ public class QueryStringQueryBuilder extends AbstractQueryBuilder<QueryStringQue
@Override @Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.field("query", this.queryString); builder.field(QueryStringQueryParser.QUERY_FIELD.getPreferredName(), this.queryString);
if (this.defaultField != null) { if (this.defaultField != null) {
builder.field("default_field", this.defaultField); builder.field(QueryStringQueryParser.DEFAULT_FIELD_FIELD.getPreferredName(), this.defaultField);
} }
builder.startArray("fields"); builder.startArray(QueryStringQueryParser.FIELDS_FIELD.getPreferredName());
for (Map.Entry<String, Float> fieldEntry : this.fieldsAndWeights.entrySet()) { for (Map.Entry<String, Float> fieldEntry : this.fieldsAndWeights.entrySet()) {
builder.value(fieldEntry.getKey() + "^" + fieldEntry.getValue()); builder.value(fieldEntry.getKey() + "^" + fieldEntry.getValue());
} }
builder.endArray(); builder.endArray();
builder.field("use_dis_max", this.useDisMax); builder.field(QueryStringQueryParser.USE_DIS_MAX_FIELD.getPreferredName(), this.useDisMax);
builder.field("tie_breaker", this.tieBreaker); builder.field(QueryStringQueryParser.TIE_BREAKER_FIELD.getPreferredName(), this.tieBreaker);
builder.field("default_operator", this.defaultOperator.name().toLowerCase(Locale.ROOT)); builder.field(QueryStringQueryParser.DEFAULT_OPERATOR_FIELD.getPreferredName(), this.defaultOperator.name().toLowerCase(Locale.ROOT));
if (this.analyzer != null) { if (this.analyzer != null) {
builder.field("analyzer", this.analyzer); builder.field(QueryStringQueryParser.ANALYZER_FIELD.getPreferredName(), this.analyzer);
} }
if (this.quoteAnalyzer != null) { if (this.quoteAnalyzer != null) {
builder.field("quote_analyzer", this.quoteAnalyzer); builder.field(QueryStringQueryParser.QUOTE_ANALYZER_FIELD.getPreferredName(), this.quoteAnalyzer);
} }
builder.field("auto_generate_phrase_queries", this.autoGeneratePhraseQueries); builder.field(QueryStringQueryParser.AUTO_GENERATED_PHRASE_QUERIES_FIELD.getPreferredName(), this.autoGeneratePhraseQueries);
builder.field("max_determinized_states", this.maxDeterminizedStates); builder.field(QueryStringQueryParser.MAX_DETERMINED_STATES_FIELD.getPreferredName(), this.maxDeterminizedStates);
if (this.allowLeadingWildcard != null) { if (this.allowLeadingWildcard != null) {
builder.field("allow_leading_wildcard", this.allowLeadingWildcard); builder.field(QueryStringQueryParser.ALLOW_LEADING_WILDCARD_FIELD.getPreferredName(), this.allowLeadingWildcard);
} }
builder.field("lowercase_expanded_terms", this.lowercaseExpandedTerms); builder.field(QueryStringQueryParser.LOWERCASE_EXPANDED_TERMS_FIELD.getPreferredName(), this.lowercaseExpandedTerms);
builder.field("enable_position_increments", this.enablePositionIncrements); builder.field(QueryStringQueryParser.ENABLE_POSITION_INCREMENTS_FIELD.getPreferredName(), this.enablePositionIncrements);
this.fuzziness.toXContent(builder, params); this.fuzziness.toXContent(builder, params);
builder.field("fuzzy_prefix_length", this.fuzzyPrefixLength); builder.field(QueryStringQueryParser.FUZZY_PREFIX_LENGTH_FIELD.getPreferredName(), this.fuzzyPrefixLength);
builder.field("fuzzy_max_expansions", this.fuzzyMaxExpansions); builder.field(QueryStringQueryParser.FUZZY_MAX_EXPANSIONS_FIELD.getPreferredName(), this.fuzzyMaxExpansions);
if (this.fuzzyRewrite != null) { if (this.fuzzyRewrite != null) {
builder.field("fuzzy_rewrite", this.fuzzyRewrite); builder.field(QueryStringQueryParser.FUZZY_REWRITE_FIELD.getPreferredName(), this.fuzzyRewrite);
} }
builder.field("phrase_slop", this.phraseSlop); builder.field(QueryStringQueryParser.PHRASE_SLOP_FIELD.getPreferredName(), this.phraseSlop);
if (this.analyzeWildcard != null) { if (this.analyzeWildcard != null) {
builder.field("analyze_wildcard", this.analyzeWildcard); builder.field(QueryStringQueryParser.ANALYZE_WILDCARD_FIELD.getPreferredName(), this.analyzeWildcard);
} }
if (this.rewrite != null) { if (this.rewrite != null) {
builder.field("rewrite", this.rewrite); builder.field(QueryStringQueryParser.REWRITE_FIELD.getPreferredName(), this.rewrite);
} }
if (this.minimumShouldMatch != null) { if (this.minimumShouldMatch != null) {
builder.field("minimum_should_match", this.minimumShouldMatch); builder.field(QueryStringQueryParser.MINIMUM_SHOULD_MATCH_FIELD.getPreferredName(), this.minimumShouldMatch);
} }
if (this.quoteFieldSuffix != null) { if (this.quoteFieldSuffix != null) {
builder.field("quote_field_suffix", this.quoteFieldSuffix); builder.field(QueryStringQueryParser.QUOTE_FIELD_SUFFIX_FIELD.getPreferredName(), this.quoteFieldSuffix);
} }
if (this.lenient != null) { if (this.lenient != null) {
builder.field("lenient", this.lenient); builder.field(QueryStringQueryParser.LENIENT_FIELD.getPreferredName(), this.lenient);
} }
builder.field("locale", this.locale.toLanguageTag()); builder.field(QueryStringQueryParser.LOCALE_FIELD.getPreferredName(), this.locale.toLanguageTag());
if (this.timeZone != null) { if (this.timeZone != null) {
builder.field("time_zone", this.timeZone.getID()); builder.field(QueryStringQueryParser.TIME_ZONE_FIELD.getPreferredName(), this.timeZone.getID());
} }
builder.field("escape", this.escape); builder.field(QueryStringQueryParser.ESCAPE_FIELD.getPreferredName(), this.escape);
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
builder.endObject(); builder.endObject();
} }

View File

@ -19,6 +19,7 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.unit.Fuzziness; import org.elasticsearch.common.unit.Fuzziness;
@ -34,6 +35,32 @@ import java.util.Map;
*/ */
public class QueryStringQueryParser implements QueryParser { public class QueryStringQueryParser implements QueryParser {
public static final ParseField QUERY_FIELD = new ParseField("query");
public static final ParseField FIELDS_FIELD = new ParseField("fields");
public static final ParseField DEFAULT_FIELD_FIELD = new ParseField("default_field");
public static final ParseField DEFAULT_OPERATOR_FIELD = new ParseField("default_operator");
public static final ParseField ANALYZER_FIELD = new ParseField("analyzer");
public static final ParseField QUOTE_ANALYZER_FIELD = new ParseField("quote_analyzer");
public static final ParseField ALLOW_LEADING_WILDCARD_FIELD = new ParseField("allow_leading_wildcard");
public static final ParseField AUTO_GENERATED_PHRASE_QUERIES_FIELD = new ParseField("auto_generated_phrase_queries");
public static final ParseField MAX_DETERMINED_STATES_FIELD = new ParseField("max_determined_states");
public static final ParseField LOWERCASE_EXPANDED_TERMS_FIELD = new ParseField("lowercase_expanded_terms");
public static final ParseField ENABLE_POSITION_INCREMENTS_FIELD = new ParseField("enable_position_increment");
public static final ParseField ESCAPE_FIELD = new ParseField("escape");
public static final ParseField USE_DIS_MAX_FIELD = new ParseField("use_dis_max");
public static final ParseField FUZZY_PREFIX_LENGTH_FIELD = new ParseField("fuzzy_prefix_length");
public static final ParseField FUZZY_MAX_EXPANSIONS_FIELD = new ParseField("fuzzy_max_expansions");
public static final ParseField FUZZY_REWRITE_FIELD = new ParseField("fuzzy_rewrite");
public static final ParseField PHRASE_SLOP_FIELD = new ParseField("phrase_slop");
public static final ParseField TIE_BREAKER_FIELD = new ParseField("tie_breaker");
public static final ParseField ANALYZE_WILDCARD_FIELD = new ParseField("analyze_wildcard");
public static final ParseField REWRITE_FIELD = new ParseField("rewrite");
public static final ParseField MINIMUM_SHOULD_MATCH_FIELD = new ParseField("minimum_should_match");
public static final ParseField QUOTE_FIELD_SUFFIX_FIELD = new ParseField("quote_field_suffix");
public static final ParseField LENIENT_FIELD = new ParseField("lenient");
public static final ParseField LOCALE_FIELD = new ParseField("locale");
public static final ParseField TIME_ZONE_FIELD = new ParseField("time_zone");
@Override @Override
public String[] names() { public String[] names() {
return new String[]{QueryStringQueryBuilder.NAME, Strings.toCamelCase(QueryStringQueryBuilder.NAME)}; return new String[]{QueryStringQueryBuilder.NAME, Strings.toCamelCase(QueryStringQueryBuilder.NAME)};
@ -76,7 +103,7 @@ public class QueryStringQueryParser implements QueryParser {
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_ARRAY) { } else if (token == XContentParser.Token.START_ARRAY) {
if ("fields".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, FIELDS_FIELD)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
String fField = null; String fField = null;
float fBoost = AbstractQueryBuilder.DEFAULT_BOOST; float fBoost = AbstractQueryBuilder.DEFAULT_BOOST;
@ -99,64 +126,64 @@ public class QueryStringQueryParser implements QueryParser {
throw new ParsingException(parser.getTokenLocation(), "[" + QueryStringQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[" + QueryStringQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]");
} }
} else if (token.isValue()) { } else if (token.isValue()) {
if ("query".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, QUERY_FIELD)) {
queryString = parser.text(); queryString = parser.text();
} else if ("default_field".equals(currentFieldName) || "defaultField".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, DEFAULT_FIELD_FIELD)) {
defaultField = parser.text(); defaultField = parser.text();
} else if ("default_operator".equals(currentFieldName) || "defaultOperator".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, DEFAULT_OPERATOR_FIELD)) {
defaultOperator = Operator.fromString(parser.text()); defaultOperator = Operator.fromString(parser.text());
} else if ("analyzer".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, ANALYZER_FIELD)) {
analyzer = parser.text(); analyzer = parser.text();
} else if ("quote_analyzer".equals(currentFieldName) || "quoteAnalyzer".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, QUOTE_ANALYZER_FIELD)) {
quoteAnalyzer = parser.text(); quoteAnalyzer = parser.text();
} else if ("allow_leading_wildcard".equals(currentFieldName) || "allowLeadingWildcard".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, ALLOW_LEADING_WILDCARD_FIELD)) {
allowLeadingWildcard = parser.booleanValue(); allowLeadingWildcard = parser.booleanValue();
} else if ("auto_generate_phrase_queries".equals(currentFieldName) || "autoGeneratePhraseQueries".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AUTO_GENERATED_PHRASE_QUERIES_FIELD)) {
autoGeneratePhraseQueries = parser.booleanValue(); autoGeneratePhraseQueries = parser.booleanValue();
} else if ("max_determinized_states".equals(currentFieldName) || "maxDeterminizedStates".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, MAX_DETERMINED_STATES_FIELD)) {
maxDeterminizedStates = parser.intValue(); maxDeterminizedStates = parser.intValue();
} else if ("lowercase_expanded_terms".equals(currentFieldName) || "lowercaseExpandedTerms".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, LOWERCASE_EXPANDED_TERMS_FIELD)) {
lowercaseExpandedTerms = parser.booleanValue(); lowercaseExpandedTerms = parser.booleanValue();
} else if ("enable_position_increments".equals(currentFieldName) || "enablePositionIncrements".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, ENABLE_POSITION_INCREMENTS_FIELD)) {
enablePositionIncrements = parser.booleanValue(); enablePositionIncrements = parser.booleanValue();
} else if ("escape".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, ESCAPE_FIELD)) {
escape = parser.booleanValue(); escape = parser.booleanValue();
} else if ("use_dis_max".equals(currentFieldName) || "useDisMax".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, USE_DIS_MAX_FIELD)) {
useDisMax = parser.booleanValue(); useDisMax = parser.booleanValue();
} else if ("fuzzy_prefix_length".equals(currentFieldName) || "fuzzyPrefixLength".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, FUZZY_PREFIX_LENGTH_FIELD)) {
fuzzyPrefixLength = parser.intValue(); fuzzyPrefixLength = parser.intValue();
} else if ("fuzzy_max_expansions".equals(currentFieldName) || "fuzzyMaxExpansions".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, FUZZY_MAX_EXPANSIONS_FIELD)) {
fuzzyMaxExpansions = parser.intValue(); fuzzyMaxExpansions = parser.intValue();
} else if ("fuzzy_rewrite".equals(currentFieldName) || "fuzzyRewrite".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, FUZZY_REWRITE_FIELD)) {
fuzzyRewrite = parser.textOrNull(); fuzzyRewrite = parser.textOrNull();
} else if ("phrase_slop".equals(currentFieldName) || "phraseSlop".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, PHRASE_SLOP_FIELD)) {
phraseSlop = parser.intValue(); phraseSlop = parser.intValue();
} else if (parseContext.parseFieldMatcher().match(currentFieldName, Fuzziness.FIELD)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, Fuzziness.FIELD)) {
fuzziness = Fuzziness.parse(parser); fuzziness = Fuzziness.parse(parser);
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else if ("tie_breaker".equals(currentFieldName) || "tieBreaker".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, TIE_BREAKER_FIELD)) {
tieBreaker = parser.floatValue(); tieBreaker = parser.floatValue();
} else if ("analyze_wildcard".equals(currentFieldName) || "analyzeWildcard".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, ANALYZE_WILDCARD_FIELD)) {
analyzeWildcard = parser.booleanValue(); analyzeWildcard = parser.booleanValue();
} else if ("rewrite".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, REWRITE_FIELD)) {
rewrite = parser.textOrNull(); rewrite = parser.textOrNull();
} else if ("minimum_should_match".equals(currentFieldName) || "minimumShouldMatch".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, MINIMUM_SHOULD_MATCH_FIELD)) {
minimumShouldMatch = parser.textOrNull(); minimumShouldMatch = parser.textOrNull();
} else if ("quote_field_suffix".equals(currentFieldName) || "quoteFieldSuffix".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, QUOTE_FIELD_SUFFIX_FIELD)) {
quoteFieldSuffix = parser.textOrNull(); quoteFieldSuffix = parser.textOrNull();
} else if ("lenient".equalsIgnoreCase(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, LENIENT_FIELD)) {
lenient = parser.booleanValue(); lenient = parser.booleanValue();
} else if ("locale".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, LOCALE_FIELD)) {
String localeStr = parser.text(); String localeStr = parser.text();
locale = Locale.forLanguageTag(localeStr); locale = Locale.forLanguageTag(localeStr);
} else if ("time_zone".equals(currentFieldName) || "timeZone".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, TIME_ZONE_FIELD)) {
try { try {
timeZone = parser.text(); timeZone = parser.text();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
throw new ParsingException(parser.getTokenLocation(), "[" + QueryStringQueryBuilder.NAME + "] time_zone [" + parser.text() + "] is unknown"); throw new ParsingException(parser.getTokenLocation(), "[" + QueryStringQueryBuilder.NAME + "] time_zone [" + parser.text() + "] is unknown");
} }
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[" + QueryStringQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[" + QueryStringQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]");

View File

@ -233,15 +233,15 @@ public class RangeQueryBuilder extends AbstractQueryBuilder<RangeQueryBuilder> i
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.startObject(fieldName); builder.startObject(fieldName);
builder.field("from", convertToStringIfBytesRef(this.from)); builder.field(RangeQueryParser.FROM_FIELD.getPreferredName(), convertToStringIfBytesRef(this.from));
builder.field("to", convertToStringIfBytesRef(this.to)); builder.field(RangeQueryParser.TO_FIELD.getPreferredName(), convertToStringIfBytesRef(this.to));
builder.field("include_lower", includeLower); builder.field(RangeQueryParser.INCLUDE_LOWER_FIELD.getPreferredName(), includeLower);
builder.field("include_upper", includeUpper); builder.field(RangeQueryParser.INCLUDE_UPPER_FIELD.getPreferredName(), includeUpper);
if (timeZone != null) { if (timeZone != null) {
builder.field("time_zone", timeZone.getID()); builder.field(RangeQueryParser.TIME_ZONE_FIELD.getPreferredName(), timeZone.getID());
} }
if (format != null) { if (format != null) {
builder.field("format", format.format()); builder.field(RangeQueryParser.FORMAT_FIELD.getPreferredName(), format.format());
} }
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
builder.endObject(); builder.endObject();

View File

@ -30,8 +30,18 @@ import java.io.IOException;
*/ */
public class RangeQueryParser implements QueryParser<RangeQueryBuilder> { public class RangeQueryParser implements QueryParser<RangeQueryBuilder> {
private static final ParseField FIELDDATA_FIELD = new ParseField("fielddata").withAllDeprecated("[no replacement]"); public static final ParseField FIELDDATA_FIELD = new ParseField("fielddata").withAllDeprecated("[no replacement]");
private static final ParseField NAME_FIELD = new ParseField("_name").withAllDeprecated("query name is not supported in short version of range query"); public static final ParseField NAME_FIELD = new ParseField("_name").withAllDeprecated("query name is not supported in short version of range query");
public static final ParseField LTE_FIELD = new ParseField("lte", "le");
public static final ParseField GTE_FIELD = new ParseField("gte", "ge");
public static final ParseField FROM_FIELD = new ParseField("from");
public static final ParseField TO_FIELD = new ParseField("to");
public static final ParseField INCLUDE_LOWER_FIELD = new ParseField("include_lower");
public static final ParseField INCLUDE_UPPER_FIELD = new ParseField("include_upper");
public static final ParseField GT_FIELD = new ParseField("gt");
public static final ParseField LT_FIELD = new ParseField("lt");
public static final ParseField TIME_ZONE_FIELD = new ParseField("time_zone");
public static final ParseField FORMAT_FIELD = new ParseField("format");
@Override @Override
public String[] names() { public String[] names() {
@ -65,33 +75,33 @@ public class RangeQueryParser implements QueryParser<RangeQueryBuilder> {
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else { } else {
if ("from".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, FROM_FIELD)) {
from = parser.objectBytes(); from = parser.objectBytes();
} else if ("to".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, TO_FIELD)) {
to = parser.objectBytes(); to = parser.objectBytes();
} else if ("include_lower".equals(currentFieldName) || "includeLower".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, INCLUDE_LOWER_FIELD)) {
includeLower = parser.booleanValue(); includeLower = parser.booleanValue();
} else if ("include_upper".equals(currentFieldName) || "includeUpper".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, INCLUDE_UPPER_FIELD)) {
includeUpper = parser.booleanValue(); includeUpper = parser.booleanValue();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else if ("gt".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, GT_FIELD)) {
from = parser.objectBytes(); from = parser.objectBytes();
includeLower = false; includeLower = false;
} else if ("gte".equals(currentFieldName) || "ge".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, GTE_FIELD)) {
from = parser.objectBytes(); from = parser.objectBytes();
includeLower = true; includeLower = true;
} else if ("lt".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, LT_FIELD)) {
to = parser.objectBytes(); to = parser.objectBytes();
includeUpper = false; includeUpper = false;
} else if ("lte".equals(currentFieldName) || "le".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, LTE_FIELD)) {
to = parser.objectBytes(); to = parser.objectBytes();
includeUpper = true; includeUpper = true;
} else if ("time_zone".equals(currentFieldName) || "timeZone".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, TIME_ZONE_FIELD)) {
timeZone = parser.text(); timeZone = parser.text();
} else if ("format".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, FORMAT_FIELD)) {
format = parser.text(); format = parser.text();
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[range] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[range] query does not support [" + currentFieldName + "]");

View File

@ -135,14 +135,14 @@ public class RegexpQueryBuilder extends AbstractQueryBuilder<RegexpQueryBuilder>
} }
@Override @Override
public void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.startObject(fieldName); builder.startObject(fieldName);
builder.field("value", this.value); builder.field(RegexpQueryParser.VALUE_FIELD.getPreferredName(), this.value);
builder.field("flags_value", flagsValue); builder.field(RegexpQueryParser.FLAGS_VALUE_FIELD.getPreferredName(), flagsValue);
builder.field("max_determinized_states", maxDeterminizedStates); builder.field(RegexpQueryParser.MAX_DETERMINIZED_STATES_FIELD.getPreferredName(), maxDeterminizedStates);
if (rewrite != null) { if (rewrite != null) {
builder.field("rewrite", rewrite); builder.field(RegexpQueryParser.REWRITE_FIELD.getPreferredName(), rewrite);
} }
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
builder.endObject(); builder.endObject();
@ -155,7 +155,7 @@ public class RegexpQueryBuilder extends AbstractQueryBuilder<RegexpQueryBuilder>
} }
@Override @Override
public Query doToQuery(QueryShardContext context) throws QueryShardException, IOException { protected Query doToQuery(QueryShardContext context) throws QueryShardException, IOException {
MultiTermQuery.RewriteMethod method = QueryParsers.parseRewriteMethod(context.parseFieldMatcher(), rewrite, null); MultiTermQuery.RewriteMethod method = QueryParsers.parseRewriteMethod(context.parseFieldMatcher(), rewrite, null);
Query query = null; Query query = null;
@ -174,7 +174,7 @@ public class RegexpQueryBuilder extends AbstractQueryBuilder<RegexpQueryBuilder>
} }
@Override @Override
public RegexpQueryBuilder doReadFrom(StreamInput in) throws IOException { protected RegexpQueryBuilder doReadFrom(StreamInput in) throws IOException {
RegexpQueryBuilder regexpQueryBuilder = new RegexpQueryBuilder(in.readString(), in.readString()); RegexpQueryBuilder regexpQueryBuilder = new RegexpQueryBuilder(in.readString(), in.readString());
regexpQueryBuilder.flagsValue = in.readVInt(); regexpQueryBuilder.flagsValue = in.readVInt();
regexpQueryBuilder.maxDeterminizedStates = in.readVInt(); regexpQueryBuilder.maxDeterminizedStates = in.readVInt();
@ -183,7 +183,7 @@ public class RegexpQueryBuilder extends AbstractQueryBuilder<RegexpQueryBuilder>
} }
@Override @Override
public void doWriteTo(StreamOutput out) throws IOException { protected void doWriteTo(StreamOutput out) throws IOException {
out.writeString(fieldName); out.writeString(fieldName);
out.writeString(value); out.writeString(value);
out.writeVInt(flagsValue); out.writeVInt(flagsValue);
@ -192,12 +192,12 @@ public class RegexpQueryBuilder extends AbstractQueryBuilder<RegexpQueryBuilder>
} }
@Override @Override
public int doHashCode() { protected int doHashCode() {
return Objects.hash(fieldName, value, flagsValue, maxDeterminizedStates, rewrite); return Objects.hash(fieldName, value, flagsValue, maxDeterminizedStates, rewrite);
} }
@Override @Override
public boolean doEquals(RegexpQueryBuilder other) { protected boolean doEquals(RegexpQueryBuilder other) {
return Objects.equals(fieldName, other.fieldName) && return Objects.equals(fieldName, other.fieldName) &&
Objects.equals(value, other.value) && Objects.equals(value, other.value) &&
Objects.equals(flagsValue, other.flagsValue) && Objects.equals(flagsValue, other.flagsValue) &&

View File

@ -30,7 +30,12 @@ import java.io.IOException;
*/ */
public class RegexpQueryParser implements QueryParser<RegexpQueryBuilder> { public class RegexpQueryParser implements QueryParser<RegexpQueryBuilder> {
private static final ParseField NAME_FIELD = new ParseField("_name").withAllDeprecated("query name is not supported in short version of regexp query"); public static final ParseField NAME_FIELD = new ParseField("_name").withAllDeprecated("query name is not supported in short version of regexp query");
public static final ParseField FLAGS_VALUE_FIELD = new ParseField("flags_value");
public static final ParseField MAX_DETERMINIZED_STATES_FIELD = new ParseField("max_determinized_states");
public static final ParseField FLAGS_FIELD = new ParseField("flags");
public static final ParseField REWRITE_FIELD = new ParseField("rewrite");
public static final ParseField VALUE_FIELD = new ParseField("value");
@Override @Override
public String[] names() { public String[] names() {
@ -62,20 +67,20 @@ public class RegexpQueryParser implements QueryParser<RegexpQueryBuilder> {
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else { } else {
if ("value".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, VALUE_FIELD)) {
value = parser.textOrNull(); value = parser.textOrNull();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else if ("rewrite".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, REWRITE_FIELD)) {
rewrite = parser.textOrNull(); rewrite = parser.textOrNull();
} else if ("flags".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, FLAGS_FIELD)) {
String flags = parser.textOrNull(); String flags = parser.textOrNull();
flagsValue = RegexpFlag.resolveValue(flags); flagsValue = RegexpFlag.resolveValue(flags);
} else if ("max_determinized_states".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, MAX_DETERMINIZED_STATES_FIELD)) {
maxDeterminizedStates = parser.intValue(); maxDeterminizedStates = parser.intValue();
} else if ("flags_value".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, FLAGS_VALUE_FIELD)) {
flagsValue = parser.intValue(); flagsValue = parser.intValue();
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[regexp] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[regexp] query does not support [" + currentFieldName + "]");

View File

@ -19,6 +19,7 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.script.Script; import org.elasticsearch.script.Script;
@ -35,6 +36,8 @@ import java.util.Map;
*/ */
public class ScriptQueryParser implements QueryParser<ScriptQueryBuilder> { public class ScriptQueryParser implements QueryParser<ScriptQueryBuilder> {
public static final ParseField PARAMS_FIELD = new ParseField("params");
@Override @Override
public String[] names() { public String[] names() {
return new String[]{ScriptQueryBuilder.NAME}; return new String[]{ScriptQueryBuilder.NAME};
@ -62,15 +65,15 @@ public class ScriptQueryParser implements QueryParser<ScriptQueryBuilder> {
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
if (parseContext.parseFieldMatcher().match(currentFieldName, ScriptField.SCRIPT)) { if (parseContext.parseFieldMatcher().match(currentFieldName, ScriptField.SCRIPT)) {
script = Script.parse(parser, parseContext.parseFieldMatcher()); script = Script.parse(parser, parseContext.parseFieldMatcher());
} else if ("params".equals(currentFieldName)) { // TODO remove in 3.0 (here to support old script APIs) } else if (parseContext.parseFieldMatcher().match(currentFieldName, PARAMS_FIELD)) { // TODO remove in 3.0 (here to support old script APIs)
params = parser.map(); params = parser.map();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[script] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[script] query does not support [" + currentFieldName + "]");
} }
} else if (token.isValue()) { } else if (token.isValue()) {
if ("_name".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else if (!scriptParameterParser.token(currentFieldName, token, parser, parseContext.parseFieldMatcher())) { } else if (!scriptParameterParser.token(currentFieldName, token, parser, parseContext.parseFieldMatcher())) {
throw new ParsingException(parser.getTokenLocation(), "[script] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[script] query does not support [" + currentFieldName + "]");

View File

@ -303,10 +303,10 @@ public class SimpleQueryStringBuilder extends AbstractQueryBuilder<SimpleQuerySt
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.field("query", queryText); builder.field(SimpleQueryStringParser.QUERY_FIELD.getPreferredName(), queryText);
if (fieldsAndWeights.size() > 0) { if (fieldsAndWeights.size() > 0) {
builder.startArray("fields"); builder.startArray(SimpleQueryStringParser.FIELDS_FIELD.getPreferredName());
for (Map.Entry<String, Float> entry : fieldsAndWeights.entrySet()) { for (Map.Entry<String, Float> entry : fieldsAndWeights.entrySet()) {
builder.value(entry.getKey() + "^" + entry.getValue()); builder.value(entry.getKey() + "^" + entry.getValue());
} }
@ -314,18 +314,18 @@ public class SimpleQueryStringBuilder extends AbstractQueryBuilder<SimpleQuerySt
} }
if (analyzer != null) { if (analyzer != null) {
builder.field("analyzer", analyzer); builder.field(SimpleQueryStringParser.ANALYZER_FIELD.getPreferredName(), analyzer);
} }
builder.field("flags", flags); builder.field(SimpleQueryStringParser.FLAGS_FIELD.getPreferredName(), flags);
builder.field("default_operator", defaultOperator.name().toLowerCase(Locale.ROOT)); builder.field(SimpleQueryStringParser.DEFAULT_OPERATOR_FIELD.getPreferredName(), defaultOperator.name().toLowerCase(Locale.ROOT));
builder.field("lowercase_expanded_terms", settings.lowercaseExpandedTerms()); builder.field(SimpleQueryStringParser.LOWERCASE_EXPANDED_TERMS_FIELD.getPreferredName(), settings.lowercaseExpandedTerms());
builder.field("lenient", settings.lenient()); builder.field(SimpleQueryStringParser.LENIENT_FIELD.getPreferredName(), settings.lenient());
builder.field("analyze_wildcard", settings.analyzeWildcard()); builder.field(SimpleQueryStringParser.ANALYZE_WILDCARD_FIELD.getPreferredName(), settings.analyzeWildcard());
builder.field("locale", (settings.locale().toLanguageTag())); builder.field(SimpleQueryStringParser.LOCALE_FIELD.getPreferredName(), (settings.locale().toLanguageTag()));
if (minimumShouldMatch != null) { if (minimumShouldMatch != null) {
builder.field("minimum_should_match", minimumShouldMatch); builder.field(SimpleQueryStringParser.MINIMUM_SHOULD_MATCH_FIELD.getPreferredName(), minimumShouldMatch);
} }
printBoostAndQueryName(builder); printBoostAndQueryName(builder);

View File

@ -19,6 +19,7 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
@ -60,6 +61,17 @@ import java.util.Map;
*/ */
public class SimpleQueryStringParser implements QueryParser<SimpleQueryStringBuilder> { public class SimpleQueryStringParser implements QueryParser<SimpleQueryStringBuilder> {
public static final ParseField MINIMUM_SHOULD_MATCH_FIELD = new ParseField("minimum_should_match");
public static final ParseField ANALYZE_WILDCARD_FIELD = new ParseField("analyze_wildcard");
public static final ParseField LENIENT_FIELD = new ParseField("lenient");
public static final ParseField LOWERCASE_EXPANDED_TERMS_FIELD = new ParseField("lowercase_expanded_terms");
public static final ParseField LOCALE_FIELD = new ParseField("locale");
public static final ParseField FLAGS_FIELD = new ParseField("flags");
public static final ParseField DEFAULT_OPERATOR_FIELD = new ParseField("default_operator");
public static final ParseField ANALYZER_FIELD = new ParseField("analyzer");
public static final ParseField QUERY_FIELD = new ParseField("query");
public static final ParseField FIELDS_FIELD = new ParseField("fields");
@Override @Override
public String[] names() { public String[] names() {
return new String[]{SimpleQueryStringBuilder.NAME, Strings.toCamelCase(SimpleQueryStringBuilder.NAME)}; return new String[]{SimpleQueryStringBuilder.NAME, Strings.toCamelCase(SimpleQueryStringBuilder.NAME)};
@ -88,7 +100,7 @@ public class SimpleQueryStringParser implements QueryParser<SimpleQueryStringBui
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_ARRAY) { } else if (token == XContentParser.Token.START_ARRAY) {
if ("fields".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, FIELDS_FIELD)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
String fField = null; String fField = null;
float fBoost = 1; float fBoost = 1;
@ -111,15 +123,15 @@ public class SimpleQueryStringParser implements QueryParser<SimpleQueryStringBui
throw new ParsingException(parser.getTokenLocation(), "[" + SimpleQueryStringBuilder.NAME + "] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[" + SimpleQueryStringBuilder.NAME + "] query does not support [" + currentFieldName + "]");
} }
} else if (token.isValue()) { } else if (token.isValue()) {
if ("query".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, QUERY_FIELD)) {
queryBody = parser.text(); queryBody = parser.text();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else if ("analyzer".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, ANALYZER_FIELD)) {
analyzerName = parser.text(); analyzerName = parser.text();
} else if ("default_operator".equals(currentFieldName) || "defaultOperator".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, DEFAULT_OPERATOR_FIELD)) {
defaultOperator = Operator.fromString(parser.text()); defaultOperator = Operator.fromString(parser.text());
} else if ("flags".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, FLAGS_FIELD)) {
if (parser.currentToken() != XContentParser.Token.VALUE_NUMBER) { if (parser.currentToken() != XContentParser.Token.VALUE_NUMBER) {
// Possible options are: // Possible options are:
// ALL, NONE, AND, OR, PREFIX, PHRASE, PRECEDENCE, ESCAPE, WHITESPACE, FUZZY, NEAR, SLOP // ALL, NONE, AND, OR, PREFIX, PHRASE, PRECEDENCE, ESCAPE, WHITESPACE, FUZZY, NEAR, SLOP
@ -130,18 +142,18 @@ public class SimpleQueryStringParser implements QueryParser<SimpleQueryStringBui
flags = SimpleQueryStringFlag.ALL.value(); flags = SimpleQueryStringFlag.ALL.value();
} }
} }
} else if ("locale".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, LOCALE_FIELD)) {
String localeStr = parser.text(); String localeStr = parser.text();
locale = Locale.forLanguageTag(localeStr); locale = Locale.forLanguageTag(localeStr);
} else if ("lowercase_expanded_terms".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, LOWERCASE_EXPANDED_TERMS_FIELD)) {
lowercaseExpandedTerms = parser.booleanValue(); lowercaseExpandedTerms = parser.booleanValue();
} else if ("lenient".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, LENIENT_FIELD)) {
lenient = parser.booleanValue(); lenient = parser.booleanValue();
} else if ("analyze_wildcard".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, ANALYZE_WILDCARD_FIELD)) {
analyzeWildcard = parser.booleanValue(); analyzeWildcard = parser.booleanValue();
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else if ("minimum_should_match".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, MINIMUM_SHOULD_MATCH_FIELD)) {
minimumShouldMatch = parser.textOrNull(); minimumShouldMatch = parser.textOrNull();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[" + SimpleQueryStringBuilder.NAME + "] unsupported field [" + parser.currentName() + "]"); throw new ParsingException(parser.getTokenLocation(), "[" + SimpleQueryStringBuilder.NAME + "] unsupported field [" + parser.currentName() + "]");

View File

@ -71,9 +71,9 @@ public class SpanContainingQueryBuilder extends AbstractQueryBuilder<SpanContain
@Override @Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.field("big"); builder.field(SpanContainingQueryParser.BIG_FIELD.getPreferredName());
big.toXContent(builder, params); big.toXContent(builder, params);
builder.field("little"); builder.field(SpanContainingQueryParser.LITTLE_FIELD.getPreferredName());
little.toXContent(builder, params); little.toXContent(builder, params);
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
builder.endObject(); builder.endObject();

View File

@ -19,6 +19,7 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
@ -30,6 +31,9 @@ import java.io.IOException;
*/ */
public class SpanContainingQueryParser implements QueryParser<SpanContainingQueryBuilder> { public class SpanContainingQueryParser implements QueryParser<SpanContainingQueryBuilder> {
public static final ParseField BIG_FIELD = new ParseField("big");
public static final ParseField LITTLE_FIELD = new ParseField("little");
@Override @Override
public String[] names() { public String[] names() {
return new String[]{SpanContainingQueryBuilder.NAME, Strings.toCamelCase(SpanContainingQueryBuilder.NAME)}; return new String[]{SpanContainingQueryBuilder.NAME, Strings.toCamelCase(SpanContainingQueryBuilder.NAME)};
@ -49,13 +53,13 @@ public class SpanContainingQueryParser implements QueryParser<SpanContainingQuer
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
if ("big".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, BIG_FIELD)) {
QueryBuilder query = parseContext.parseInnerQueryBuilder(); QueryBuilder query = parseContext.parseInnerQueryBuilder();
if (!(query instanceof SpanQueryBuilder<?>)) { if (!(query instanceof SpanQueryBuilder<?>)) {
throw new ParsingException(parser.getTokenLocation(), "span_containing [big] must be of type span query"); throw new ParsingException(parser.getTokenLocation(), "span_containing [big] must be of type span query");
} }
big = (SpanQueryBuilder<?>) query; big = (SpanQueryBuilder<?>) query;
} else if ("little".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, LITTLE_FIELD)) {
QueryBuilder query = parseContext.parseInnerQueryBuilder(); QueryBuilder query = parseContext.parseInnerQueryBuilder();
if (!(query instanceof SpanQueryBuilder<?>)) { if (!(query instanceof SpanQueryBuilder<?>)) {
throw new ParsingException(parser.getTokenLocation(), "span_containing [little] must be of type span query"); throw new ParsingException(parser.getTokenLocation(), "span_containing [little] must be of type span query");
@ -64,9 +68,9 @@ public class SpanContainingQueryParser implements QueryParser<SpanContainingQuer
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[span_containing] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[span_containing] query does not support [" + currentFieldName + "]");
} }
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[span_containing] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[span_containing] query does not support [" + currentFieldName + "]");

View File

@ -74,9 +74,9 @@ public class SpanFirstQueryBuilder extends AbstractQueryBuilder<SpanFirstQueryBu
@Override @Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.field("match"); builder.field(SpanFirstQueryParser.MATCH_FIELD.getPreferredName());
matchBuilder.toXContent(builder, params); matchBuilder.toXContent(builder, params);
builder.field("end", end); builder.field(SpanFirstQueryParser.END_FIELD.getPreferredName(), end);
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
builder.endObject(); builder.endObject();
} }

View File

@ -19,6 +19,7 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
@ -30,6 +31,9 @@ import java.io.IOException;
*/ */
public class SpanFirstQueryParser implements QueryParser<SpanFirstQueryBuilder> { public class SpanFirstQueryParser implements QueryParser<SpanFirstQueryBuilder> {
public static final ParseField MATCH_FIELD = new ParseField("match");
public static final ParseField END_FIELD = new ParseField("end");
@Override @Override
public String[] names() { public String[] names() {
return new String[]{SpanFirstQueryBuilder.NAME, Strings.toCamelCase(SpanFirstQueryBuilder.NAME)}; return new String[]{SpanFirstQueryBuilder.NAME, Strings.toCamelCase(SpanFirstQueryBuilder.NAME)};
@ -51,7 +55,7 @@ public class SpanFirstQueryParser implements QueryParser<SpanFirstQueryBuilder>
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
if ("match".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, MATCH_FIELD)) {
QueryBuilder query = parseContext.parseInnerQueryBuilder(); QueryBuilder query = parseContext.parseInnerQueryBuilder();
if (!(query instanceof SpanQueryBuilder)) { if (!(query instanceof SpanQueryBuilder)) {
throw new ParsingException(parser.getTokenLocation(), "spanFirst [match] must be of type span query"); throw new ParsingException(parser.getTokenLocation(), "spanFirst [match] must be of type span query");
@ -61,11 +65,11 @@ public class SpanFirstQueryParser implements QueryParser<SpanFirstQueryBuilder>
throw new ParsingException(parser.getTokenLocation(), "[span_first] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[span_first] query does not support [" + currentFieldName + "]");
} }
} else { } else {
if ("boost".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else if ("end".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, END_FIELD)) {
end = parser.intValue(); end = parser.intValue();
} else if ("_name".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[span_first] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[span_first] query does not support [" + currentFieldName + "]");

View File

@ -56,7 +56,7 @@ public class SpanMultiTermQueryBuilder extends AbstractQueryBuilder<SpanMultiTer
protected void doXContent(XContentBuilder builder, Params params) protected void doXContent(XContentBuilder builder, Params params)
throws IOException { throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.field(SpanMultiTermQueryParser.MATCH_NAME); builder.field(SpanMultiTermQueryParser.MATCH_FIELD.getPreferredName());
multiTermQueryBuilder.toXContent(builder, params); multiTermQueryBuilder.toXContent(builder, params);
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
builder.endObject(); builder.endObject();

View File

@ -18,6 +18,7 @@
*/ */
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
@ -29,7 +30,7 @@ import java.io.IOException;
*/ */
public class SpanMultiTermQueryParser implements QueryParser<SpanMultiTermQueryBuilder> { public class SpanMultiTermQueryParser implements QueryParser<SpanMultiTermQueryBuilder> {
public static final String MATCH_NAME = "match"; public static final ParseField MATCH_FIELD = new ParseField("match");
@Override @Override
public String[] names() { public String[] names() {
@ -48,19 +49,19 @@ public class SpanMultiTermQueryParser implements QueryParser<SpanMultiTermQueryB
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
if (MATCH_NAME.equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, MATCH_FIELD)) {
QueryBuilder innerQuery = parseContext.parseInnerQueryBuilder(); QueryBuilder innerQuery = parseContext.parseInnerQueryBuilder();
if (innerQuery instanceof MultiTermQueryBuilder == false) { if (innerQuery instanceof MultiTermQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), "[span_multi] [" + MATCH_NAME + "] must be of type multi term query"); throw new ParsingException(parser.getTokenLocation(), "[span_multi] [" + MATCH_FIELD.getPreferredName() + "] must be of type multi term query");
} }
subQuery = (MultiTermQueryBuilder) innerQuery; subQuery = (MultiTermQueryBuilder) innerQuery;
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[span_multi] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[span_multi] query does not support [" + currentFieldName + "]");
} }
} else if (token.isValue()) { } else if (token.isValue()) {
if ("_name".equals(currentFieldName)) { if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text(); queryName = parser.text();
} else if ("boost".equals(currentFieldName)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue(); boost = parser.floatValue();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[span_multi] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[span_multi] query does not support [" + currentFieldName + "]");
@ -69,7 +70,7 @@ public class SpanMultiTermQueryParser implements QueryParser<SpanMultiTermQueryB
} }
if (subQuery == null) { if (subQuery == null) {
throw new ParsingException(parser.getTokenLocation(), "[span_multi] must have [" + MATCH_NAME + "] multi term query clause"); throw new ParsingException(parser.getTokenLocation(), "[span_multi] must have [" + MATCH_FIELD.getPreferredName() + "] multi term query clause");
} }
return new SpanMultiTermQueryBuilder(subQuery).queryName(queryName).boost(boost); return new SpanMultiTermQueryBuilder(subQuery).queryName(queryName).boost(boost);

View File

@ -125,14 +125,14 @@ public class SpanNearQueryBuilder extends AbstractQueryBuilder<SpanNearQueryBuil
@Override @Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME); builder.startObject(NAME);
builder.startArray("clauses"); builder.startArray(SpanNearQueryParser.CLAUSES_FIELD.getPreferredName());
for (SpanQueryBuilder clause : clauses) { for (SpanQueryBuilder clause : clauses) {
clause.toXContent(builder, params); clause.toXContent(builder, params);
} }
builder.endArray(); builder.endArray();
builder.field("slop", slop); builder.field(SpanNearQueryParser.SLOP_FIELD.getPreferredName(), slop);
builder.field("in_order", inOrder); builder.field(SpanNearQueryParser.IN_ORDER_FIELD.getPreferredName(), inOrder);
builder.field("collect_payloads", collectPayloads); builder.field(SpanNearQueryParser.COLLECT_PAYLOADS_FIELD.getPreferredName(), collectPayloads);
printBoostAndQueryName(builder); printBoostAndQueryName(builder);
builder.endObject(); builder.endObject();
} }

Some files were not shown because too many files have changed in this diff Show More