@Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    MultiSearchRequest multiSearchRequest = new MultiSearchRequest();
    multiSearchRequest.listenerThreaded(false);

    String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    String[] types = Strings.splitStringByCommaToArray(request.param("type"));
    IndicesOptions indicesOptions =
        IndicesOptions.fromRequest(request, multiSearchRequest.indicesOptions());

    try {
      multiSearchRequest.add(
          request.content(),
          request.contentUnsafe(),
          indices,
          types,
          request.param("search_type"),
          request.param("routing"),
          indicesOptions,
          allowExplicitIndex);
    } catch (Exception e) {
      try {
        XContentBuilder builder = restContentBuilder(request);
        channel.sendResponse(
            new XContentRestResponse(
                request,
                BAD_REQUEST,
                builder.startObject().field("error", e.getMessage()).endObject()));
      } catch (IOException e1) {
        logger.error("Failed to send failure response", e1);
      }
      return;
    }

    client.multiSearch(
        multiSearchRequest,
        new ActionListener<MultiSearchResponse>() {
          @Override
          public void onResponse(MultiSearchResponse response) {
            try {
              XContentBuilder builder = restContentBuilder(request);
              builder.startObject();
              response.toXContent(builder, request);
              builder.endObject();
              channel.sendResponse(new XContentRestResponse(request, OK, builder));
            } catch (Throwable e) {
              onFailure(e);
            }
          }

          @Override
          public void onFailure(Throwable e) {
            try {
              channel.sendResponse(new XContentThrowableRestResponse(request, e));
            } catch (IOException e1) {
              logger.error("Failed to send failure response", e1);
            }
          }
        });
  }
 /**
  * Build a random search request.
  *
  * @param randomSearchSourceBuilder builds a random {@link SearchSourceBuilder}. You can use
  *     {@link #randomSearchSourceBuilder(Supplier, Supplier, Supplier, Supplier)}.
  */
 public static SearchRequest randomSearchRequest(
     Supplier<SearchSourceBuilder> randomSearchSourceBuilder) throws IOException {
   SearchRequest searchRequest = new SearchRequest();
   if (randomBoolean()) {
     searchRequest.indices(generateRandomStringArray(10, 10, false, false));
   }
   if (randomBoolean()) {
     searchRequest.indicesOptions(
         IndicesOptions.fromOptions(
             randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean()));
   }
   if (randomBoolean()) {
     searchRequest.types(generateRandomStringArray(10, 10, false, false));
   }
   if (randomBoolean()) {
     searchRequest.preference(randomAsciiOfLengthBetween(3, 10));
   }
   if (randomBoolean()) {
     searchRequest.requestCache(randomBoolean());
   }
   if (randomBoolean()) {
     searchRequest.routing(randomAsciiOfLengthBetween(3, 10));
   }
   if (randomBoolean()) {
     searchRequest.scroll(randomPositiveTimeValue());
   }
   if (randomBoolean()) {
     searchRequest.searchType(randomFrom(SearchType.values()));
   }
   if (randomBoolean()) {
     searchRequest.source(randomSearchSourceBuilder.get());
   }
   return searchRequest;
 }
 @Override
 public void writeTo(StreamOutput out) throws IOException {
   super.writeTo(out);
   out.writeStringArray(indices);
   out.writeStringArray(aliases);
   indicesOptions.writeIndicesOptions(out);
 }
 @Override
 public void readFrom(StreamInput in) throws IOException {
   super.readFrom(in);
   indices = in.readStringArray();
   aliases = in.readStringArray();
   indicesOptions = IndicesOptions.readIndicesOptions(in);
 }
  private RestChannelConsumer parseExistingDocPercolate(
      PercolateRequest percolateRequest, RestRequest restRequest, NodeClient client) {
    String index = restRequest.param("index");
    String type = restRequest.param("type");
    percolateRequest.indices(
        Strings.splitStringByCommaToArray(restRequest.param("percolate_index", index)));
    percolateRequest.documentType(restRequest.param("percolate_type", type));

    GetRequest getRequest = new GetRequest(index, type, restRequest.param("id"));
    getRequest.routing(restRequest.param("routing"));
    getRequest.preference(restRequest.param("preference"));
    getRequest.refresh(restRequest.paramAsBoolean("refresh", getRequest.refresh()));
    getRequest.realtime(restRequest.paramAsBoolean("realtime", getRequest.realtime()));
    getRequest.version(RestActions.parseVersion(restRequest));
    getRequest.versionType(
        VersionType.fromString(restRequest.param("version_type"), getRequest.versionType()));

    percolateRequest.getRequest(getRequest);
    percolateRequest.routing(restRequest.param("percolate_routing"));
    percolateRequest.preference(restRequest.param("percolate_preference"));
    percolateRequest.source(restRequest.contentOrSourceParam());

    percolateRequest.indicesOptions(
        IndicesOptions.fromRequest(restRequest, percolateRequest.indicesOptions()));
    return channel -> executePercolate(client, percolateRequest, channel);
  }
 public ESDeletePartitionTask(
     UUID jobId, TransportDeleteIndexAction transport, ESDeletePartitionNode node) {
   super(jobId);
   this.transport = transport;
   this.request = new DeleteIndexRequest(node.indices());
   if (node.indices().length > 1) {
     /**
      * table is partitioned, in case of concurrent "delete from partitions" it could be that some
      * partitions are already deleted, so ignore it if some are missing
      */
     this.request.indicesOptions(IndicesOptions.lenientExpandOpen());
   } else {
     this.request.indicesOptions(IndicesOptions.strictExpandOpen());
   }
   this.listener = new DeleteIndexListener(result);
 }
 @Test
 public void testDeleteByQueryWithNoIndices() {
   DeleteByQueryRequestBuilder delete = newDeleteByQuery().setQuery(QueryBuilders.matchAllQuery());
   delete.setIndicesOptions(IndicesOptions.fromOptions(false, true, true, false));
   assertDBQResponse(delete.get(), 0L, 0l, 0l, 0l);
   assertSearchContextsClosed();
 }
 @Override
 public void handleRequest(
     final RestRequest request, final RestChannel channel, final NodeClient client) {
   ForceMergeRequest mergeRequest =
       new ForceMergeRequest(Strings.splitStringByCommaToArray(request.param("index")));
   mergeRequest.indicesOptions(IndicesOptions.fromRequest(request, mergeRequest.indicesOptions()));
   mergeRequest.maxNumSegments(
       request.paramAsInt("max_num_segments", mergeRequest.maxNumSegments()));
   mergeRequest.onlyExpungeDeletes(
       request.paramAsBoolean("only_expunge_deletes", mergeRequest.onlyExpungeDeletes()));
   mergeRequest.flush(request.paramAsBoolean("flush", mergeRequest.flush()));
   client
       .admin()
       .indices()
       .forceMerge(
           mergeRequest,
           new RestBuilderListener<ForceMergeResponse>(channel) {
             @Override
             public RestResponse buildResponse(
                 ForceMergeResponse response, XContentBuilder builder) throws Exception {
               builder.startObject();
               buildBroadcastShardsHeader(builder, request, response);
               builder.endObject();
               return new BytesRestResponse(OK, builder);
             }
           });
 }
示例#9
0
  // Duel between histograms and scripted terms
  public void testDuelTermsHistogram() throws Exception {
    createIndex("idx");

    final int numDocs = scaledRandomIntBetween(500, 5000);
    final int maxNumTerms = randomIntBetween(10, 2000);
    final int interval = randomIntBetween(1, 100);

    final Integer[] values = new Integer[maxNumTerms];
    for (int i = 0; i < values.length; ++i) {
      values[i] = randomInt(maxNumTerms * 3) - maxNumTerms;
    }

    for (int i = 0; i < numDocs; ++i) {
      XContentBuilder source =
          jsonBuilder().startObject().field("num", randomDouble()).startArray("values");
      final int numValues = randomInt(4);
      for (int j = 0; j < numValues; ++j) {
        source = source.value(randomFrom(values));
      }
      source = source.endArray().endObject();
      client().prepareIndex("idx", "type").setSource(source).execute().actionGet();
    }
    assertNoFailures(
        client()
            .admin()
            .indices()
            .prepareRefresh("idx")
            .setIndicesOptions(IndicesOptions.lenientExpandOpen())
            .execute()
            .get());

    SearchResponse resp =
        client()
            .prepareSearch("idx")
            .addAggregation(
                terms("terms")
                    .field("values")
                    .collectMode(randomFrom(SubAggCollectionMode.values()))
                    .script("floor(_value / interval)")
                    .param("interval", interval)
                    .size(maxNumTerms))
            .addAggregation(histogram("histo").field("values").interval(interval))
            .execute()
            .actionGet();

    assertSearchResponse(resp);

    Terms terms = resp.getAggregations().get("terms");
    assertThat(terms, notNullValue());
    Histogram histo = resp.getAggregations().get("histo");
    assertThat(histo, notNullValue());
    assertThat(terms.getBuckets().size(), equalTo(histo.getBuckets().size()));
    for (Terms.Bucket bucket : terms.getBuckets()) {
      final long key = bucket.getKeyAsNumber().longValue() * interval;
      final Histogram.Bucket histoBucket = histo.getBucketByKey(key);
      assertEquals(bucket.getDocCount(), histoBucket.getDocCount());
    }
  }
  @Test
  public void testSerialization() throws Exception {
    int iterations = randomIntBetween(5, 20);
    for (int i = 0; i < iterations; i++) {

      IndicesOptions indicesOptions =
          IndicesOptions.fromOptions(
              randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean());
      ClusterStateRequest clusterStateRequest =
          new ClusterStateRequest()
              .routingTable(randomBoolean())
              .metaData(randomBoolean())
              .nodes(randomBoolean())
              .blocks(randomBoolean())
              .indices("testindex", "testindex2")
              .indicesOptions(indicesOptions);

      Version testVersion =
          VersionUtils.randomVersionBetween(
              random(), Version.CURRENT.minimumCompatibilityVersion(), Version.CURRENT);
      BytesStreamOutput output = new BytesStreamOutput();
      output.setVersion(testVersion);
      clusterStateRequest.writeTo(output);

      StreamInput streamInput = StreamInput.wrap(output.bytes());
      streamInput.setVersion(testVersion);
      ClusterStateRequest deserializedCSRequest = new ClusterStateRequest();
      deserializedCSRequest.readFrom(streamInput);

      assertThat(deserializedCSRequest.routingTable(), equalTo(clusterStateRequest.routingTable()));
      assertThat(deserializedCSRequest.metaData(), equalTo(clusterStateRequest.metaData()));
      assertThat(deserializedCSRequest.nodes(), equalTo(clusterStateRequest.nodes()));
      assertThat(deserializedCSRequest.blocks(), equalTo(clusterStateRequest.blocks()));
      assertThat(deserializedCSRequest.indices(), equalTo(clusterStateRequest.indices()));

      if (testVersion.onOrAfter(Version.V_1_5_0)) {
        assertOptionsMatch(
            deserializedCSRequest.indicesOptions(), clusterStateRequest.indicesOptions());
      } else {
        // versions before V_1_5_0 use IndicesOptions.lenientExpandOpen()
        assertOptionsMatch(
            deserializedCSRequest.indicesOptions(), IndicesOptions.lenientExpandOpen());
      }
    }
  }
示例#11
0
 public static OriginalIndices readOptionalOriginalIndices(StreamInput in) throws IOException {
   if (in.getVersion().onOrAfter(Version.V_1_4_0_Beta1)) {
     boolean empty = in.readBoolean();
     if (!empty) {
       return new OriginalIndices(in.readStringArray(), IndicesOptions.readIndicesOptions(in));
     }
   }
   return OriginalIndices.EMPTY;
 }
 @Override
 public void readFrom(StreamInput in) throws IOException {
   super.readFrom(in);
   replicationType = ReplicationType.fromId(in.readByte());
   consistencyLevel = WriteConsistencyLevel.fromId(in.readByte());
   timeout = TimeValue.readTimeValue(in);
   indices = in.readStringArray();
   indicesOptions = IndicesOptions.readIndicesOptions(in);
 }
 @Override
 public void writeTo(StreamOutput out) throws IOException {
   super.writeTo(out);
   out.writeByte(replicationType.id());
   out.writeByte(consistencyLevel.id());
   timeout.writeTo(out);
   out.writeStringArrayNullable(indices);
   indicesOptions.writeIndicesOptions(out);
 }
  @Override
  protected void masterOperation(
      final ClusterStateRequest request,
      final ClusterState state,
      ActionListener<ClusterStateResponse> listener)
      throws ElasticsearchException {
    ClusterState currentState = clusterService.state();
    logger.trace("Serving cluster state request using version {}", currentState.version());
    ClusterState.Builder builder = ClusterState.builder(currentState.getClusterName());
    builder.version(currentState.version());
    if (request.nodes()) {
      builder.nodes(currentState.nodes());
    }
    if (request.routingTable()) {
      if (request.indices().length > 0) {
        RoutingTable.Builder routingTableBuilder = RoutingTable.builder();
        for (String filteredIndex : request.indices()) {
          if (currentState.routingTable().getIndicesRouting().containsKey(filteredIndex)) {
            routingTableBuilder.add(
                currentState.routingTable().getIndicesRouting().get(filteredIndex));
          }
        }
        builder.routingTable(routingTableBuilder);
      } else {
        builder.routingTable(currentState.routingTable());
      }
    }
    if (request.blocks()) {
      builder.blocks(currentState.blocks());
    }
    if (request.metaData()) {
      MetaData.Builder mdBuilder;
      if (request.indices().length == 0) {
        mdBuilder = MetaData.builder(currentState.metaData());
      } else {
        mdBuilder = MetaData.builder();
      }

      if (request.indices().length > 0) {
        String[] indices =
            currentState
                .metaData()
                .concreteIndices(IndicesOptions.lenientExpandOpen(), request.indices());
        for (String filteredIndex : indices) {
          IndexMetaData indexMetaData = currentState.metaData().index(filteredIndex);
          if (indexMetaData != null) {
            mdBuilder.put(indexMetaData, false);
          }
        }
      }

      builder.metaData(mdBuilder);
    }
    listener.onResponse(new ClusterStateResponse(clusterName, builder.build()));
  }
  private RestChannelConsumer parseDocPercolate(
      PercolateRequest percolateRequest, RestRequest restRequest, NodeClient client) {
    percolateRequest.indices(Strings.splitStringByCommaToArray(restRequest.param("index")));
    percolateRequest.documentType(restRequest.param("type"));
    percolateRequest.routing(restRequest.param("routing"));
    percolateRequest.preference(restRequest.param("preference"));
    percolateRequest.source(restRequest.contentOrSourceParam());

    percolateRequest.indicesOptions(
        IndicesOptions.fromRequest(restRequest, percolateRequest.indicesOptions()));
    return channel -> executePercolate(client, percolateRequest, channel);
  }
 @Test
 public void testIndexNameFiltering() {
   assertIndexNameFiltering(
       new String[] {"foo", "bar", "baz"}, new String[] {}, new String[] {"foo", "bar", "baz"});
   assertIndexNameFiltering(
       new String[] {"foo", "bar", "baz"}, new String[] {"*"}, new String[] {"foo", "bar", "baz"});
   assertIndexNameFiltering(
       new String[] {"foo", "bar", "baz"},
       new String[] {"foo", "bar", "baz"},
       new String[] {"foo", "bar", "baz"});
   assertIndexNameFiltering(
       new String[] {"foo", "bar", "baz"}, new String[] {"foo"}, new String[] {"foo"});
   assertIndexNameFiltering(
       new String[] {"foo", "bar", "baz"}, new String[] {"ba*", "-bar", "-baz"}, new String[] {});
   assertIndexNameFiltering(
       new String[] {"foo", "bar", "baz"}, new String[] {"-bar"}, new String[] {"foo", "baz"});
   assertIndexNameFiltering(
       new String[] {"foo", "bar", "baz"}, new String[] {"-ba*"}, new String[] {"foo"});
   assertIndexNameFiltering(
       new String[] {"foo", "bar", "baz"}, new String[] {"+ba*"}, new String[] {"bar", "baz"});
   assertIndexNameFiltering(
       new String[] {"foo", "bar", "baz"},
       new String[] {"+bar", "+foo"},
       new String[] {"bar", "foo"});
   assertIndexNameFiltering(
       new String[] {"foo", "bar", "baz"},
       new String[] {"zzz", "bar"},
       IndicesOptions.lenientExpandOpen(),
       new String[] {"bar"});
   assertIndexNameFiltering(
       new String[] {"foo", "bar", "baz"},
       new String[] {""},
       IndicesOptions.lenientExpandOpen(),
       new String[] {});
   assertIndexNameFiltering(
       new String[] {"foo", "bar", "baz"},
       new String[] {"foo", "", "ba*"},
       IndicesOptions.lenientExpandOpen(),
       new String[] {"foo", "bar", "baz"});
 }
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
    final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(aliases);
    getAliasesRequest.indices(indices);
    getAliasesRequest.indicesOptions(
        IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
    getAliasesRequest.local(request.paramAsBoolean("local", getAliasesRequest.local()));

    client
        .admin()
        .indices()
        .getAliases(
            getAliasesRequest,
            new RestBuilderListener<GetAliasesResponse>(channel) {
              @Override
              public RestResponse buildResponse(
                  GetAliasesResponse response, XContentBuilder builder) throws Exception {
                // empty body, if indices were specified but no aliases were
                if (indices.length > 0 && response.getAliases().isEmpty()) {
                  return new BytesRestResponse(OK, builder.startObject().endObject());
                } else if (response.getAliases().isEmpty()) {
                  String message =
                      String.format(
                          Locale.ROOT,
                          "alias [%s] missing",
                          toNamesString(getAliasesRequest.aliases()));
                  builder
                      .startObject()
                      .field("error", message)
                      .field("status", RestStatus.NOT_FOUND.getStatus())
                      .endObject();
                  return new BytesRestResponse(RestStatus.NOT_FOUND, builder);
                }

                builder.startObject();
                for (ObjectObjectCursor<String, List<AliasMetaData>> entry :
                    response.getAliases()) {
                  builder.startObject(entry.key, XContentBuilder.FieldCaseConversion.NONE);
                  builder.startObject(Fields.ALIASES);
                  for (AliasMetaData alias : entry.value) {
                    AliasMetaData.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
                  }
                  builder.endObject();
                  builder.endObject();
                }
                builder.endObject();
                return new BytesRestResponse(OK, builder);
              }
            });
  }
 @Override
 public void writeTo(StreamOutput out) throws IOException {
   super.writeTo(out);
   out.writeString(snapshot);
   out.writeString(repository);
   out.writeStringArray(indices);
   indicesOptions.writeIndicesOptions(out);
   out.writeOptionalString(renamePattern);
   out.writeOptionalString(renameReplacement);
   out.writeBoolean(waitForCompletion);
   out.writeBoolean(includeGlobalState);
   writeSettingsToStream(settings, out);
 }
 @Override
 public void readFrom(StreamInput in) throws IOException {
   super.readFrom(in);
   snapshot = in.readString();
   repository = in.readString();
   indices = in.readStringArray();
   indicesOptions = IndicesOptions.readIndicesOptions(in);
   renamePattern = in.readOptionalString();
   renameReplacement = in.readOptionalString();
   waitForCompletion = in.readBoolean();
   includeGlobalState = in.readBoolean();
   settings = readSettingsFromStream(in);
 }
示例#20
0
  private DocIndexMetaData docIndexMetaData() {
    DocIndexMetaData docIndexMetaData;
    String templateName = PartitionName.templateName(ident.schema(), ident.name());
    boolean createdFromTemplate = false;
    if (metaData.getTemplates().containsKey(templateName)) {
      docIndexMetaData = buildDocIndexMetaDataFromTemplate(ident.indexName(), templateName);
      createdFromTemplate = true;
      concreteIndices =
          metaData.concreteIndices(IndicesOptions.lenientExpandOpen(), ident.indexName());
    } else {
      try {
        concreteIndices =
            metaData.concreteIndices(IndicesOptions.strictExpandOpen(), ident.indexName());
        if (concreteIndices.length == 0) {
          // no matching index found
          throw new TableUnknownException(ident);
        }
        docIndexMetaData = buildDocIndexMetaData(concreteIndices[0]);
      } catch (IndexMissingException ex) {
        throw new TableUnknownException(ident.fqn(), ex);
      }
    }

    if ((!createdFromTemplate && concreteIndices.length == 1) || !checkAliasSchema) {
      return docIndexMetaData;
    }
    for (int i = 0; i < concreteIndices.length; i++) {
      try {
        docIndexMetaData =
            docIndexMetaData.merge(
                buildDocIndexMetaData(concreteIndices[i]),
                transportPutIndexTemplateAction,
                createdFromTemplate);
      } catch (IOException e) {
        throw new UnhandledServerException("Unable to merge/build new DocIndexMetaData", e);
      }
    }
    return docIndexMetaData;
  }
 @Override
 public void handleRequest(
     final RestRequest request, final RestChannel channel, final Client client)
     throws IOException {
   final SearchRequest searchRequest =
       new SearchRequest(
           Strings.splitStringByCommaToArray(request.param("index")), new SearchSourceBuilder());
   searchRequest.indicesOptions(
       IndicesOptions.fromRequest(request, searchRequest.indicesOptions()));
   if (RestActions.hasBodyContent(request)) {
     final BytesReference sourceBytes = RestActions.getRestContent(request);
     try (XContentParser parser =
         XContentFactory.xContent(sourceBytes).createParser(sourceBytes)) {
       final QueryParseContext context =
           new QueryParseContext(queryRegistry, parser, parseFieldMatcher);
       searchRequest.source().suggest(SuggestBuilder.fromXContent(context, suggesters));
     }
   } else {
     throw new IllegalArgumentException("no content or source provided to execute suggestion");
   }
   searchRequest.routing(request.param("routing"));
   searchRequest.preference(request.param("preference"));
   client.search(
       searchRequest,
       new RestBuilderListener<SearchResponse>(channel) {
         @Override
         public RestResponse buildResponse(SearchResponse response, XContentBuilder builder)
             throws Exception {
           RestStatus restStatus =
               RestStatus.status(
                   response.getSuccessfulShards(),
                   response.getTotalShards(),
                   response.getShardFailures());
           builder.startObject();
           buildBroadcastShardsHeader(
               builder,
               request,
               response.getTotalShards(),
               response.getSuccessfulShards(),
               response.getFailedShards(),
               response.getShardFailures());
           Suggest suggest = response.getSuggest();
           if (suggest != null) {
             suggest.toInnerXContent(builder, request);
           }
           builder.endObject();
           return new BytesRestResponse(restStatus, builder);
         }
       });
 }
  void parseDocPercolate(
      PercolateRequest percolateRequest,
      RestRequest restRequest,
      RestChannel restChannel,
      final Client client) {
    percolateRequest.indices(Strings.splitStringByCommaToArray(restRequest.param("index")));
    percolateRequest.documentType(restRequest.param("type"));
    percolateRequest.routing(restRequest.param("routing"));
    percolateRequest.preference(restRequest.param("preference"));
    percolateRequest.source(RestActions.getRestContent(restRequest));

    percolateRequest.indicesOptions(
        IndicesOptions.fromRequest(restRequest, percolateRequest.indicesOptions()));
    executePercolate(percolateRequest, restChannel, client);
  }
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    final ClusterSearchShardsRequest clusterSearchShardsRequest =
        Requests.clusterSearchShardsRequest(indices);
    clusterSearchShardsRequest.local(
        request.paramAsBoolean("local", clusterSearchShardsRequest.local()));
    clusterSearchShardsRequest.listenerThreaded(false);

    clusterSearchShardsRequest.types(Strings.splitStringByCommaToArray(request.param("type")));
    clusterSearchShardsRequest.routing(request.param("routing"));
    clusterSearchShardsRequest.preference(request.param("preference"));
    clusterSearchShardsRequest.indicesOptions(
        IndicesOptions.fromRequest(request, clusterSearchShardsRequest.indicesOptions()));

    client
        .admin()
        .cluster()
        .searchShards(
            clusterSearchShardsRequest,
            new ActionListener<ClusterSearchShardsResponse>() {
              @Override
              public void onResponse(ClusterSearchShardsResponse response) {
                try {
                  XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
                  builder.startObject();
                  response.toXContent(builder, request);
                  builder.endObject();
                  channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));
                } catch (Throwable e) {
                  onFailure(e);
                }
              }

              @Override
              public void onFailure(Throwable e) {
                try {
                  channel.sendResponse(new BytesRestResponse(request, e));
                } catch (IOException e1) {
                  logger.error("Failed to send failure response", e1);
                }
              }
            });
  }
 public MultiSearchRequest add(
     byte[] data,
     int from,
     int length,
     boolean contentUnsafe,
     @Nullable String[] indices,
     @Nullable String[] types,
     @Nullable String searchType)
     throws Exception {
   return add(
       new BytesArray(data, from, length),
       contentUnsafe,
       indices,
       types,
       searchType,
       null,
       IndicesOptions.strictExpandOpenAndForbidClosed(),
       true);
 }
 @Override
 public void handleRequest(final RestRequest request, final RestChannel channel) {
   PutWarmerRequest putWarmerRequest = new PutWarmerRequest(request.param("name"));
   putWarmerRequest.listenerThreaded(false);
   SearchRequest searchRequest =
       new SearchRequest(Strings.splitStringByCommaToArray(request.param("index")))
           .types(Strings.splitStringByCommaToArray(request.param("type")))
           .source(request.content(), request.contentUnsafe());
   searchRequest.indicesOptions(
       IndicesOptions.fromRequest(request, searchRequest.indicesOptions()));
   putWarmerRequest.searchRequest(searchRequest);
   putWarmerRequest.timeout(request.paramAsTime("timeout", putWarmerRequest.timeout()));
   putWarmerRequest.masterNodeTimeout(
       request.paramAsTime("master_timeout", putWarmerRequest.masterNodeTimeout()));
   client
       .admin()
       .indices()
       .putWarmer(
           putWarmerRequest, new AcknowledgedRestResponseActionListener(request, channel, logger));
 }
示例#26
0
  public static SearchRequest parseSearchRequest(RestRequest request) {
    String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    SearchRequest searchRequest = new SearchRequest(indices);
    // get the content, and put it in the body
    // add content/source as template if template flag is set
    boolean isTemplateRequest = request.path().endsWith("/template");
    if (RestActions.hasBodyContent(request)) {
      if (isTemplateRequest) {
        searchRequest.templateSource(RestActions.getRestContent(request));
      } else {
        searchRequest.source(RestActions.getRestContent(request));
      }
    }

    // do not allow 'query_and_fetch' or 'dfs_query_and_fetch' search types
    // from the REST layer. these modes are an internal optimization and should
    // not be specified explicitly by the user.
    String searchType = request.param("search_type");
    if (SearchType.fromString(searchType).equals(SearchType.QUERY_AND_FETCH)
        || SearchType.fromString(searchType).equals(SearchType.DFS_QUERY_AND_FETCH)) {
      throw new IllegalArgumentException("Unsupported search type [" + searchType + "]");
    } else {
      searchRequest.searchType(searchType);
    }

    searchRequest.extraSource(parseSearchSource(request));
    searchRequest.queryCache(request.paramAsBoolean("query_cache", null));

    String scroll = request.param("scroll");
    if (scroll != null) {
      searchRequest.scroll(new Scroll(parseTimeValue(scroll, null, "scroll")));
    }

    searchRequest.types(Strings.splitStringByCommaToArray(request.param("type")));
    searchRequest.routing(request.param("routing"));
    searchRequest.preference(request.param("preference"));
    searchRequest.indicesOptions(
        IndicesOptions.fromRequest(request, searchRequest.indicesOptions()));

    return searchRequest;
  }
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    TypesExistsRequest typesExistsRequest =
        new TypesExistsRequest(
            Strings.splitStringByCommaToArray(request.param("index")),
            Strings.splitStringByCommaToArray(request.param("type")));
    typesExistsRequest.listenerThreaded(false);
    typesExistsRequest.local(request.paramAsBoolean("local", typesExistsRequest.local()));
    typesExistsRequest.indicesOptions(
        IndicesOptions.fromRequest(request, typesExistsRequest.indicesOptions()));
    client
        .admin()
        .indices()
        .typesExists(
            typesExistsRequest,
            new ActionListener<TypesExistsResponse>() {
              @Override
              public void onResponse(TypesExistsResponse response) {
                try {
                  if (response.isExists()) {
                    channel.sendResponse(new BytesRestResponse(OK));
                  } else {
                    channel.sendResponse(new BytesRestResponse(NOT_FOUND));
                  }
                } catch (Throwable e) {
                  onFailure(e);
                }
              }

              @Override
              public void onFailure(Throwable e) {
                try {
                  channel.sendResponse(new BytesRestResponse(ExceptionsHelper.status(e)));
                } catch (Exception e1) {
                  logger.error("Failed to send failure response", e1);
                }
              }
            });
  }
  public void testDeleteByQueryWithMissingIndex() throws Exception {
    client()
        .prepareIndex("test", "test")
        .setSource(jsonBuilder().startObject().field("field1", 1).endObject())
        .setRefresh(true)
        .get();
    assertHitCount(client().prepareSearch().setSize(0).get(), 1);

    DeleteByQueryRequestBuilder delete =
        newDeleteByQuery().setIndices("test", "missing").setQuery(QueryBuilders.matchAllQuery());
    try {
      delete.get();
      fail("should have thrown an exception because of a missing index");
    } catch (IndexNotFoundException e) {
      // Ok
    }

    delete.setIndicesOptions(IndicesOptions.lenientExpandOpen());
    assertDBQResponse(delete.get(), 1L, 1L, 0L, 0L);
    refresh();
    assertHitCount(client().prepareSearch("test").setSize(0).get(), 0);
    assertSearchContextsClosed();
  }
 @Override
 public void handleRequest(
     final RestRequest request, final RestChannel channel, final Client client)
     throws IOException {
   DeleteByQueryRequest delete =
       new DeleteByQueryRequest(Strings.splitStringByCommaToArray(request.param("index")));
   delete.indicesOptions(IndicesOptions.fromRequest(request, delete.indicesOptions()));
   delete.routing(request.param("routing"));
   if (request.hasParam("timeout")) {
     delete.timeout(request.paramAsTime("timeout", null));
   }
   if (request.hasContent()) {
     XContentParser requestParser =
         XContentFactory.xContent(request.content()).createParser(request.content());
     QueryParseContext context = new QueryParseContext(indicesQueriesRegistry);
     context.reset(requestParser);
     context.parseFieldMatcher(parseFieldMatcher);
     final QueryBuilder<?> builder = context.parseInnerQueryBuilder();
     delete.query(builder);
   } else {
     String source = request.param("source");
     if (source != null) {
       XContentParser requestParser = XContentFactory.xContent(source).createParser(source);
       QueryParseContext context = new QueryParseContext(indicesQueriesRegistry);
       context.reset(requestParser);
       final QueryBuilder<?> builder = context.parseInnerQueryBuilder();
       delete.query(builder);
     } else {
       QueryBuilder<?> queryBuilder = RestActions.urlParamsToQueryBuilder(request);
       if (queryBuilder != null) {
         delete.query(queryBuilder);
       }
     }
   }
   delete.types(Strings.splitStringByCommaToArray(request.param("type")));
   client.execute(INSTANCE, delete, new RestToXContentListener<DeleteByQueryResponse>(channel));
 }
public class MultiSearchTemplateRequest extends ActionRequest<MultiSearchTemplateRequest>
    implements CompositeIndicesRequest {

  private List<SearchTemplateRequest> requests = new ArrayList<>();

  private IndicesOptions indicesOptions = IndicesOptions.strictExpandOpenAndForbidClosed();

  /**
   * Add a search template request to execute. Note, the order is important, the search response
   * will be returned in the same order as the search requests.
   */
  public MultiSearchTemplateRequest add(SearchTemplateRequestBuilder request) {
    requests.add(request.request());
    return this;
  }

  /**
   * Add a search template request to execute. Note, the order is important, the search response
   * will be returned in the same order as the search requests.
   */
  public MultiSearchTemplateRequest add(SearchTemplateRequest request) {
    requests.add(request);
    return this;
  }

  public List<SearchTemplateRequest> requests() {
    return this.requests;
  }

  @Override
  public List<? extends IndicesRequest> subRequests() {
    return requests;
  }

  @Override
  public ActionRequestValidationException validate() {
    ActionRequestValidationException validationException = null;
    if (requests.isEmpty()) {
      validationException = addValidationError("no requests added", validationException);
    }
    for (SearchTemplateRequest request : requests) {
      ActionRequestValidationException ex = request.validate();
      if (ex != null) {
        if (validationException == null) {
          validationException = new ActionRequestValidationException();
        }
        validationException.addValidationErrors(ex.validationErrors());
      }
    }
    return validationException;
  }

  public IndicesOptions indicesOptions() {
    return indicesOptions;
  }

  public MultiSearchTemplateRequest indicesOptions(IndicesOptions indicesOptions) {
    this.indicesOptions = indicesOptions;
    return this;
  }

  @Override
  public void readFrom(StreamInput in) throws IOException {
    super.readFrom(in);
    requests = in.readStreamableList(SearchTemplateRequest::new);
  }

  @Override
  public void writeTo(StreamOutput out) throws IOException {
    super.writeTo(out);
    out.writeStreamableList(requests);
  }
}