public void testMultiGet() throws ExecutionException, InterruptedException {
    createIndexWithAlias();
    ensureYellow("test");

    int numDocs = iterations(10, 50);
    IndexRequestBuilder[] indexRequestBuilders = new IndexRequestBuilder[numDocs];
    for (int i = 0; i < numDocs; i++) {
      indexRequestBuilders[i] =
          client()
              .prepareIndex("test", "type", Integer.toString(i))
              .setSource("field", "value" + Integer.toString(i));
    }
    indexRandom(false, indexRequestBuilders);

    int iterations = iterations(1, numDocs);
    MultiGetRequestBuilder multiGetRequestBuilder = client().prepareMultiGet();
    for (int i = 0; i < iterations; i++) {
      multiGetRequestBuilder.add(
          new MultiGetRequest.Item(
              indexOrAlias(), "type", Integer.toString(randomInt(numDocs - 1))));
    }
    MultiGetResponse multiGetResponse = multiGetRequestBuilder.get();
    assertThat(multiGetResponse.getResponses().length, equalTo(iterations));
    for (int i = 0; i < multiGetResponse.getResponses().length; i++) {
      MultiGetItemResponse multiGetItemResponse = multiGetResponse.getResponses()[i];
      assertThat(multiGetItemResponse.isFailed(), equalTo(false));
      assertThat(multiGetItemResponse.getIndex(), equalTo("test"));
      assertThat(multiGetItemResponse.getType(), equalTo("type"));
      assertThat(
          multiGetItemResponse.getId(),
          equalTo(multiGetRequestBuilder.request().getItems().get(i).id()));
      assertThat(multiGetItemResponse.getResponse().isExists(), equalTo(true));
      assertThat(multiGetItemResponse.getResponse().getIndex(), equalTo("test"));
      assertThat(multiGetItemResponse.getResponse().getType(), equalTo("type"));
      assertThat(
          multiGetItemResponse.getResponse().getId(),
          equalTo(multiGetRequestBuilder.request().getItems().get(i).id()));
    }
  }
Example #2
0
  public List<DOMAIN> getByKeys(Collection<KEY> keys) {
    if (keys.isEmpty()) {
      return Collections.emptyList();
    }
    List<DOMAIN> results = new ArrayList<>();
    MultiGetRequestBuilder request = client.prepareMultiGet().setPreference("_local");
    for (KEY key : keys) {
      request.add(
          new MultiGetRequest.Item(getIndexName(), getIndexType(), getKeyValue(key))
              .routing(getKeyValue(key))
              .fetchSourceContext(FetchSourceContext.FETCH_SOURCE));
    }

    MultiGetResponse response = request.get();
    if (response.getResponses() != null) {
      for (MultiGetItemResponse item : response.getResponses()) {
        Map<String, Object> source = item.getResponse().getSource();
        if (source != null) {
          results.add(toDoc(source));
        }
      }
    }
    return results;
  }