Search in sources :

Example 21 with GetResponse

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.action.get.GetResponse in project elasticsearch by elastic.

the class CrudIT method testGet.

public void testGet() throws IOException {
    {
        GetRequest getRequest = new GetRequest("index", "type", "id");
        ElasticsearchException exception = expectThrows(ElasticsearchException.class, () -> execute(getRequest, highLevelClient()::get, highLevelClient()::getAsync));
        assertEquals(RestStatus.NOT_FOUND, exception.status());
        assertEquals("Elasticsearch exception [type=index_not_found_exception, reason=no such index]", exception.getMessage());
        assertEquals("index", exception.getMetadata("es.index").get(0));
    }
    String document = "{\"field1\":\"value1\",\"field2\":\"value2\"}";
    StringEntity stringEntity = new StringEntity(document, ContentType.APPLICATION_JSON);
    Response response = client().performRequest("PUT", "/index/type/id", Collections.singletonMap("refresh", "wait_for"), stringEntity);
    assertEquals(201, response.getStatusLine().getStatusCode());
    {
        GetRequest getRequest = new GetRequest("index", "type", "id").version(2);
        ElasticsearchException exception = expectThrows(ElasticsearchException.class, () -> execute(getRequest, highLevelClient()::get, highLevelClient()::getAsync));
        assertEquals(RestStatus.CONFLICT, exception.status());
        assertEquals("Elasticsearch exception [type=version_conflict_engine_exception, " + "reason=[type][id]: " + "version conflict, current version [1] is different than the one provided [2]]", exception.getMessage());
        assertEquals("index", exception.getMetadata("es.index").get(0));
    }
    {
        GetRequest getRequest = new GetRequest("index", "type", "id");
        if (randomBoolean()) {
            getRequest.version(1L);
        }
        GetResponse getResponse = execute(getRequest, highLevelClient()::get, highLevelClient()::getAsync);
        assertEquals("index", getResponse.getIndex());
        assertEquals("type", getResponse.getType());
        assertEquals("id", getResponse.getId());
        assertTrue(getResponse.isExists());
        assertFalse(getResponse.isSourceEmpty());
        assertEquals(1L, getResponse.getVersion());
        assertEquals(document, getResponse.getSourceAsString());
    }
    {
        GetRequest getRequest = new GetRequest("index", "type", "does_not_exist");
        GetResponse getResponse = execute(getRequest, highLevelClient()::get, highLevelClient()::getAsync);
        assertEquals("index", getResponse.getIndex());
        assertEquals("type", getResponse.getType());
        assertEquals("does_not_exist", getResponse.getId());
        assertFalse(getResponse.isExists());
        assertEquals(-1, getResponse.getVersion());
        assertTrue(getResponse.isSourceEmpty());
        assertNull(getResponse.getSourceAsString());
    }
    {
        GetRequest getRequest = new GetRequest("index", "type", "id");
        getRequest.fetchSourceContext(new FetchSourceContext(false, Strings.EMPTY_ARRAY, Strings.EMPTY_ARRAY));
        GetResponse getResponse = execute(getRequest, highLevelClient()::get, highLevelClient()::getAsync);
        assertEquals("index", getResponse.getIndex());
        assertEquals("type", getResponse.getType());
        assertEquals("id", getResponse.getId());
        assertTrue(getResponse.isExists());
        assertTrue(getResponse.isSourceEmpty());
        assertEquals(1L, getResponse.getVersion());
        assertNull(getResponse.getSourceAsString());
    }
    {
        GetRequest getRequest = new GetRequest("index", "type", "id");
        if (randomBoolean()) {
            getRequest.fetchSourceContext(new FetchSourceContext(true, new String[] { "field1" }, Strings.EMPTY_ARRAY));
        } else {
            getRequest.fetchSourceContext(new FetchSourceContext(true, Strings.EMPTY_ARRAY, new String[] { "field2" }));
        }
        GetResponse getResponse = execute(getRequest, highLevelClient()::get, highLevelClient()::getAsync);
        assertEquals("index", getResponse.getIndex());
        assertEquals("type", getResponse.getType());
        assertEquals("id", getResponse.getId());
        assertTrue(getResponse.isExists());
        assertFalse(getResponse.isSourceEmpty());
        assertEquals(1L, getResponse.getVersion());
        Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
        assertEquals(1, sourceAsMap.size());
        assertEquals("value1", sourceAsMap.get("field1"));
    }
}
Also used : GetResponse(org.elasticsearch.action.get.GetResponse) UpdateResponse(org.elasticsearch.action.update.UpdateResponse) IndexResponse(org.elasticsearch.action.index.IndexResponse) DeleteResponse(org.elasticsearch.action.delete.DeleteResponse) BulkItemResponse(org.elasticsearch.action.bulk.BulkItemResponse) BulkResponse(org.elasticsearch.action.bulk.BulkResponse) DocWriteResponse(org.elasticsearch.action.DocWriteResponse) StringEntity(org.apache.http.entity.StringEntity) FetchSourceContext(org.elasticsearch.search.fetch.subphase.FetchSourceContext) GetRequest(org.elasticsearch.action.get.GetRequest) ElasticsearchException(org.elasticsearch.ElasticsearchException) GetResponse(org.elasticsearch.action.get.GetResponse) Map(java.util.Map) Collections.singletonMap(java.util.Collections.singletonMap)

Example 22 with GetResponse

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.action.get.GetResponse in project sonarqube by SonarSource.

the class UserIndex method getNullableByLogin.

@CheckForNull
public UserDoc getNullableByLogin(String login) {
    GetRequestBuilder request = esClient.prepareGet(UserIndexDefinition.INDEX_TYPE_USER, login).setFetchSource(true).setRouting(login);
    GetResponse response = request.get();
    if (response.isExists()) {
        return DOC_CONVERTER.apply(response.getSource());
    }
    return null;
}
Also used : GetResponse(org.elasticsearch.action.get.GetResponse) GetRequestBuilder(org.elasticsearch.action.get.GetRequestBuilder) CheckForNull(javax.annotation.CheckForNull)

Example 23 with GetResponse

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.action.get.GetResponse in project crate by crate.

the class InsertIntoIntegrationTest method testInsertWithPrimaryKey.

@Test
public void testInsertWithPrimaryKey() throws Exception {
    this.setup.createTestTableWithPrimaryKey();
    Object[] args = new Object[] { "1", "A towel is about the most massively useful thing an interstellar hitch hiker can have." };
    execute("insert into test (pk_col, message) values (?, ?)", args);
    refresh();
    GetResponse response = client().prepareGet("test", "default", "1").execute().actionGet();
    assertTrue(response.getSourceAsMap().containsKey("message"));
}
Also used : GetResponse(org.elasticsearch.action.get.GetResponse) Test(org.junit.Test)

Example 24 with GetResponse

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.action.get.GetResponse in project elasticsearch by elastic.

the class SimpleRoutingIT method testRequiredRoutingCrudApis.

public void testRequiredRoutingCrudApis() throws Exception {
    client().admin().indices().prepareCreate("test").addAlias(new Alias("alias")).addMapping("type1", XContentFactory.jsonBuilder().startObject().startObject("type1").startObject("_routing").field("required", true).endObject().endObject().endObject()).execute().actionGet();
    ensureGreen();
    logger.info("--> indexing with id [1], and routing [0]");
    client().prepareIndex(indexOrAlias(), "type1", "1").setRouting("0").setSource("field", "value1").setRefreshPolicy(RefreshPolicy.IMMEDIATE).get();
    logger.info("--> verifying get with no routing, should fail");
    logger.info("--> indexing with id [1], with no routing, should fail");
    try {
        client().prepareIndex(indexOrAlias(), "type1", "1").setSource("field", "value1").get();
        fail("index with missing routing when routing is required should fail");
    } catch (ElasticsearchException e) {
        assertThat(e.unwrapCause(), instanceOf(RoutingMissingException.class));
    }
    logger.info("--> verifying get with routing, should find");
    for (int i = 0; i < 5; i++) {
        assertThat(client().prepareGet(indexOrAlias(), "type1", "1").setRouting("0").execute().actionGet().isExists(), equalTo(true));
    }
    logger.info("--> deleting with no routing, should fail");
    try {
        client().prepareDelete(indexOrAlias(), "type1", "1").get();
        fail("delete with missing routing when routing is required should fail");
    } catch (ElasticsearchException e) {
        assertThat(e.unwrapCause(), instanceOf(RoutingMissingException.class));
    }
    for (int i = 0; i < 5; i++) {
        try {
            client().prepareGet(indexOrAlias(), "type1", "1").execute().actionGet().isExists();
            fail("get with missing routing when routing is required should fail");
        } catch (RoutingMissingException e) {
            assertThat(e.status(), equalTo(RestStatus.BAD_REQUEST));
            assertThat(e.getMessage(), equalTo("routing is required for [test]/[type1]/[1]"));
        }
        assertThat(client().prepareGet(indexOrAlias(), "type1", "1").setRouting("0").execute().actionGet().isExists(), equalTo(true));
    }
    try {
        client().prepareUpdate(indexOrAlias(), "type1", "1").setDoc(Requests.INDEX_CONTENT_TYPE, "field", "value2").execute().actionGet();
        fail("update with missing routing when routing is required should fail");
    } catch (ElasticsearchException e) {
        assertThat(e.unwrapCause(), instanceOf(RoutingMissingException.class));
    }
    client().prepareUpdate(indexOrAlias(), "type1", "1").setRouting("0").setDoc(Requests.INDEX_CONTENT_TYPE, "field", "value2").get();
    client().admin().indices().prepareRefresh().execute().actionGet();
    for (int i = 0; i < 5; i++) {
        try {
            client().prepareGet(indexOrAlias(), "type1", "1").execute().actionGet().isExists();
            fail();
        } catch (RoutingMissingException e) {
            assertThat(e.status(), equalTo(RestStatus.BAD_REQUEST));
            assertThat(e.getMessage(), equalTo("routing is required for [test]/[type1]/[1]"));
        }
        GetResponse getResponse = client().prepareGet(indexOrAlias(), "type1", "1").setRouting("0").execute().actionGet();
        assertThat(getResponse.isExists(), equalTo(true));
        assertThat(getResponse.getSourceAsMap().get("field"), equalTo("value2"));
    }
    client().prepareDelete(indexOrAlias(), "type1", "1").setRouting("0").setRefreshPolicy(RefreshPolicy.IMMEDIATE).get();
    for (int i = 0; i < 5; i++) {
        try {
            client().prepareGet(indexOrAlias(), "type1", "1").execute().actionGet().isExists();
            fail();
        } catch (RoutingMissingException e) {
            assertThat(e.status(), equalTo(RestStatus.BAD_REQUEST));
            assertThat(e.getMessage(), equalTo("routing is required for [test]/[type1]/[1]"));
        }
        assertThat(client().prepareGet(indexOrAlias(), "type1", "1").setRouting("0").execute().actionGet().isExists(), equalTo(false));
    }
}
Also used : Alias(org.elasticsearch.action.admin.indices.alias.Alias) ElasticsearchException(org.elasticsearch.ElasticsearchException) GetResponse(org.elasticsearch.action.get.GetResponse) MultiGetResponse(org.elasticsearch.action.get.MultiGetResponse) RoutingMissingException(org.elasticsearch.action.RoutingMissingException)

Example 25 with GetResponse

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.action.get.GetResponse in project elasticsearch by elastic.

the class SimpleNestedIT method testMultiNested.

public void testMultiNested() throws Exception {
    assertAcked(prepareCreate("test").addMapping("type1", jsonBuilder().startObject().startObject("type1").startObject("properties").startObject("nested1").field("type", "nested").startObject("properties").startObject("nested2").field("type", "nested").endObject().endObject().endObject().endObject().endObject().endObject()));
    ensureGreen();
    client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject().field("field", "value").startArray("nested1").startObject().field("field1", "1").startArray("nested2").startObject().field("field2", "2").endObject().startObject().field("field2", "3").endObject().endArray().endObject().startObject().field("field1", "4").startArray("nested2").startObject().field("field2", "5").endObject().startObject().field("field2", "6").endObject().endArray().endObject().endArray().endObject()).execute().actionGet();
    // flush, so we fetch it from the index (as see that we filter nested docs)
    flush();
    GetResponse getResponse = client().prepareGet("test", "type1", "1").execute().actionGet();
    assertThat(getResponse.isExists(), equalTo(true));
    waitForRelocation(ClusterHealthStatus.GREEN);
    // check the numDocs
    assertDocumentCount("test", 7);
    // do some multi nested queries
    SearchResponse searchResponse = client().prepareSearch("test").setQuery(nestedQuery("nested1", termQuery("nested1.field1", "1"), ScoreMode.Avg)).execute().actionGet();
    assertNoFailures(searchResponse);
    assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));
    searchResponse = client().prepareSearch("test").setQuery(nestedQuery("nested1.nested2", termQuery("nested1.nested2.field2", "2"), ScoreMode.Avg)).execute().actionGet();
    assertNoFailures(searchResponse);
    assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));
    searchResponse = client().prepareSearch("test").setQuery(nestedQuery("nested1", boolQuery().must(termQuery("nested1.field1", "1")).must(nestedQuery("nested1.nested2", termQuery("nested1.nested2.field2", "2"), ScoreMode.Avg)), ScoreMode.Avg)).execute().actionGet();
    assertNoFailures(searchResponse);
    assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));
    searchResponse = client().prepareSearch("test").setQuery(nestedQuery("nested1", boolQuery().must(termQuery("nested1.field1", "1")).must(nestedQuery("nested1.nested2", termQuery("nested1.nested2.field2", "3"), ScoreMode.Avg)), ScoreMode.Avg)).execute().actionGet();
    assertNoFailures(searchResponse);
    assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));
    searchResponse = client().prepareSearch("test").setQuery(nestedQuery("nested1", boolQuery().must(termQuery("nested1.field1", "1")).must(nestedQuery("nested1.nested2", termQuery("nested1.nested2.field2", "4"), ScoreMode.Avg)), ScoreMode.Avg)).execute().actionGet();
    assertNoFailures(searchResponse);
    assertThat(searchResponse.getHits().getTotalHits(), equalTo(0L));
    searchResponse = client().prepareSearch("test").setQuery(nestedQuery("nested1", boolQuery().must(termQuery("nested1.field1", "1")).must(nestedQuery("nested1.nested2", termQuery("nested1.nested2.field2", "5"), ScoreMode.Avg)), ScoreMode.Avg)).execute().actionGet();
    assertNoFailures(searchResponse);
    assertThat(searchResponse.getHits().getTotalHits(), equalTo(0L));
    searchResponse = client().prepareSearch("test").setQuery(nestedQuery("nested1", boolQuery().must(termQuery("nested1.field1", "4")).must(nestedQuery("nested1.nested2", termQuery("nested1.nested2.field2", "5"), ScoreMode.Avg)), ScoreMode.Avg)).execute().actionGet();
    assertNoFailures(searchResponse);
    assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));
    searchResponse = client().prepareSearch("test").setQuery(nestedQuery("nested1", boolQuery().must(termQuery("nested1.field1", "4")).must(nestedQuery("nested1.nested2", termQuery("nested1.nested2.field2", "2"), ScoreMode.Avg)), ScoreMode.Avg)).execute().actionGet();
    assertNoFailures(searchResponse);
    assertThat(searchResponse.getHits().getTotalHits(), equalTo(0L));
}
Also used : GetResponse(org.elasticsearch.action.get.GetResponse) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Aggregations

GetResponse (org.elasticsearch.action.get.GetResponse)149 Test (org.junit.Test)41 Map (java.util.Map)27 MultiGetResponse (org.elasticsearch.action.get.MultiGetResponse)25 ArrayList (java.util.ArrayList)22 HashMap (java.util.HashMap)18 ESSyncConfig (com.alibaba.otter.canal.client.adapter.es.core.config.ESSyncConfig)17 Dml (com.alibaba.otter.canal.client.adapter.support.Dml)17 Date (java.util.Date)17 LinkedHashMap (java.util.LinkedHashMap)17 DataSource (javax.sql.DataSource)14 GetRequestBuilder (org.elasticsearch.action.get.GetRequestBuilder)14 SearchResponse (org.elasticsearch.action.search.SearchResponse)13 DeleteResponse (org.elasticsearch.action.delete.DeleteResponse)12 IOException (java.io.IOException)11 GetRequest (org.elasticsearch.action.get.GetRequest)11 ElasticsearchException (org.elasticsearch.ElasticsearchException)9 Settings (org.elasticsearch.common.settings.Settings)9 Alias (org.elasticsearch.action.admin.indices.alias.Alias)7 UpdateResponse (org.elasticsearch.action.update.UpdateResponse)7