org.elasticsearch.action.DocWriteResponse.Result Java Examples

The following examples show how to use org.elasticsearch.action.DocWriteResponse.Result. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ElasticSearchManualTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenContentBuilder_whenHelpers_thanIndexJson() throws IOException {
    XContentBuilder builder = XContentFactory.jsonBuilder()
        .startObject()
        .field("fullName", "Test")
        .field("salary", "11500")
        .field("age", "10")
        .endObject();

    IndexRequest indexRequest = new IndexRequest("people");
    indexRequest.source(builder);

    IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);

    assertEquals(Result.CREATED, response.getResult());
}
 
Example #2
Source File: ElasticSearchManualTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenDocumentId_whenJavaObject_thenDeleteDocument() throws Exception {
    String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}";
    IndexRequest indexRequest = new IndexRequest("people");
    indexRequest.source(jsonObject, XContentType.JSON);

    IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
    String id = response.getId();

    GetRequest getRequest = new GetRequest("people");
    getRequest.id(id);

    GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
    System.out.println(getResponse.getSourceAsString());

    DeleteRequest deleteRequest = new DeleteRequest("people");
    deleteRequest.id(id);

    DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);

    assertEquals(Result.DELETED, deleteResponse.getResult());
}
 
Example #3
Source File: ElasticsearchTransportFactory.java    From database-transform-tool with Apache License 2.0 6 votes vote down vote up
public String insert(String index,String type,Object json){
	try {
		if(client==null){
			init();
		}
		IndexResponse response = client.prepareIndex(index, type).setSource(JSON.parseObject(JSON.toJSONString(json)),XContentType.JSON).execute().actionGet();
		if(response.getResult().equals(Result.CREATED)){
			System.out.println(JSON.toJSONString(response));
		}
		return response.toString();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
}
 
Example #4
Source File: DetectorMappingRepositoryImplTest.java    From adaptive-alerting with Apache License 2.0 6 votes vote down vote up
private DeleteResponse mockDeleteResponse(String id) {
    DeleteResponse deleteResponse = mock(DeleteResponse.class);
    Result ResultOpt;
    when(deleteResponse.getId()).thenReturn(id);
    String indexName = elasticSearchProperties.getIndexName();
    when(deleteResponse.getIndex()).thenReturn(indexName);
    try {
        byte[] byteopt = new byte[]{2}; // 2 - DELETED, DeleteResponse.Result
        ByteBuffer byteBuffer = ByteBuffer.wrap(byteopt);
        ByteBufferStreamInput byteoptbytebufferstream = new ByteBufferStreamInput(byteBuffer);
        ResultOpt = DocWriteResponse.Result.readFrom(byteoptbytebufferstream);
        when(deleteResponse.getResult()).thenReturn(ResultOpt);
    } catch (IOException e) {
    }
    return deleteResponse;
}
 
Example #5
Source File: LegacyDetectorRepositoryImplTest.java    From adaptive-alerting with Apache License 2.0 6 votes vote down vote up
private DeleteResponse mockDeleteResponse(String id) {
    DeleteResponse deleteResponse = mock(DeleteResponse.class);
    Result ResultOpt;
    when(deleteResponse.getId()).thenReturn(id);
    String indexName = "index";
    when(deleteResponse.getIndex()).thenReturn(indexName);
    try {
        byte[] byteOpt = new byte[]{2}; // 2 - DELETED, DeleteResponse.Result
        ByteBuffer byteBuffer = ByteBuffer.wrap(byteOpt);
        ByteBufferStreamInput byteOptBufferStream = new ByteBufferStreamInput(byteBuffer);
        ResultOpt = DocWriteResponse.Result.readFrom(byteOptBufferStream);
        when(deleteResponse.getResult()).thenReturn(ResultOpt);
    } catch (IOException e) {
    }
    return deleteResponse;
}
 
Example #6
Source File: ElasticsearchClusterRunner.java    From elasticsearch-cluster-runner with Apache License 2.0 5 votes vote down vote up
@Deprecated
public IndexResponse insert(final String index, final String type, final String id,
        final BuilderCallback<IndexRequestBuilder> builder) {
    final IndexResponse actionGet = builder.apply(client().prepareIndex(index, type, id)).execute().actionGet();
    if (actionGet.getResult() != Result.CREATED) {
        onFailure("Failed to insert " + id + " into " + index + "/" + type + ".", actionGet);
    }
    return actionGet;
}
 
Example #7
Source File: EsAbstractBehavior.java    From fess with Apache License 2.0 5 votes vote down vote up
@Override
protected int delegateDelete(final Entity entity, final DeleteOption<? extends ConditionBean> option) {
    final EsAbstractEntity esEntity = (EsAbstractEntity) entity;
    final DeleteRequestBuilder builder = createDeleteRequest(esEntity);

    final DeleteResponse response = builder.execute().actionGet(deleteTimeout);
    return response.getResult() == Result.DELETED ? 1 : 0;
}
 
Example #8
Source File: EsAbstractBehavior.java    From fess with Apache License 2.0 5 votes vote down vote up
@Override
protected int delegateInsert(final Entity entity, final InsertOption<? extends ConditionBean> option) {
    final EsAbstractEntity esEntity = (EsAbstractEntity) entity;
    IndexRequestBuilder builder = createInsertRequest(esEntity);

    final IndexResponse response = builder.execute().actionGet(indexTimeout);
    esEntity.asDocMeta().id(response.getId());
    return response.getResult() == Result.CREATED ? 1 : 0;
}
 
Example #9
Source File: FessEsClient.java    From fess with Apache License 2.0 5 votes vote down vote up
public boolean delete(final String index, final String id, final Number seqNo, final Number primaryTerm) {
    try {
        final DeleteRequestBuilder builder = client.prepareDelete().setIndex(index).setId(id).setRefreshPolicy(RefreshPolicy.IMMEDIATE);
        if (seqNo != null) {
            builder.setIfSeqNo(seqNo.longValue());
        }
        if (primaryTerm != null) {
            builder.setIfPrimaryTerm(primaryTerm.longValue());
        }
        final DeleteResponse response = builder.execute().actionGet(ComponentUtil.getFessConfig().getIndexDeleteTimeout());
        return response.getResult() == Result.DELETED;
    } catch (final ElasticsearchException e) {
        throw new FessEsClientException("Failed to delete: " + index + "/" + id + "@" + seqNo + ":" + primaryTerm, e);
    }
}
 
Example #10
Source File: FessEsClient.java    From fess with Apache License 2.0 5 votes vote down vote up
public boolean store(final String index, final Object obj) {
    final FessConfig fessConfig = ComponentUtil.getFessConfig();
    @SuppressWarnings("unchecked")
    final Map<String, Object> source = obj instanceof Map ? (Map<String, Object>) obj : BeanUtil.copyBeanToNewMap(obj);
    final String id = (String) source.remove(fessConfig.getIndexFieldId());
    source.remove(fessConfig.getIndexFieldVersion());
    final Number seqNo = (Number) source.remove(fessConfig.getIndexFieldSeqNo());
    final Number primaryTerm = (Number) source.remove(fessConfig.getIndexFieldPrimaryTerm());
    IndexResponse response;
    try {
        if (id == null) {
            // TODO throw Exception in next release
            // create
            response =
                    client.prepareIndex().setIndex(index).setSource(new DocMap(source)).setRefreshPolicy(RefreshPolicy.IMMEDIATE)
                            .setOpType(OpType.CREATE).execute().actionGet(fessConfig.getIndexIndexTimeout());
        } else {
            // create or update
            final IndexRequestBuilder builder =
                    client.prepareIndex().setIndex(index).setId(id).setSource(new DocMap(source))
                            .setRefreshPolicy(RefreshPolicy.IMMEDIATE).setOpType(OpType.INDEX);
            if (seqNo != null) {
                builder.setIfSeqNo(seqNo.longValue());
            }
            if (primaryTerm != null) {
                builder.setIfPrimaryTerm(primaryTerm.longValue());
            }
            response = builder.execute().actionGet(fessConfig.getIndexIndexTimeout());
        }
        final Result result = response.getResult();
        return result == Result.CREATED || result == Result.UPDATED;
    } catch (final ElasticsearchException e) {
        throw new FessEsClientException("Failed to store: " + obj, e);
    }
}
 
Example #11
Source File: FessEsClient.java    From fess with Apache License 2.0 5 votes vote down vote up
public boolean update(final String index, final String id, final String field, final Object value) {
    try {
        final Result result =
                client.prepareUpdate().setIndex(index).setId(id).setDoc(field, value).execute()
                        .actionGet(ComponentUtil.getFessConfig().getIndexIndexTimeout()).getResult();
        return result == Result.CREATED || result == Result.UPDATED;
    } catch (final ElasticsearchException e) {
        throw new FessEsClientException("Failed to set " + value + " to " + field + " for doc " + id, e);
    }
}
 
Example #12
Source File: EsAbstractBehavior.java    From fess with Apache License 2.0 5 votes vote down vote up
@Override
protected int delegateDelete(final Entity entity, final DeleteOption<? extends ConditionBean> option) {
    final EsAbstractEntity esEntity = (EsAbstractEntity) entity;
    final DeleteRequestBuilder builder = createDeleteRequest(esEntity);

    final DeleteResponse response = builder.execute().actionGet(deleteTimeout);
    return response.getResult() == Result.DELETED ? 1 : 0;
}
 
Example #13
Source File: EsAbstractBehavior.java    From fess with Apache License 2.0 5 votes vote down vote up
@Override
protected int delegateInsert(final Entity entity, final InsertOption<? extends ConditionBean> option) {
    final EsAbstractEntity esEntity = (EsAbstractEntity) entity;
    IndexRequestBuilder builder = createInsertRequest(esEntity);

    final IndexResponse response = builder.execute().actionGet(indexTimeout);
    esEntity.asDocMeta().id(response.getId());
    return response.getResult() == Result.CREATED ? 1 : 0;
}
 
Example #14
Source File: EsAbstractBehavior.java    From fess with Apache License 2.0 5 votes vote down vote up
@Override
protected int delegateDelete(final Entity entity, final DeleteOption<? extends ConditionBean> option) {
    final EsAbstractEntity esEntity = (EsAbstractEntity) entity;
    final DeleteRequestBuilder builder = createDeleteRequest(esEntity);

    final DeleteResponse response = builder.execute().actionGet(deleteTimeout);
    return response.getResult() == Result.DELETED ? 1 : 0;
}
 
Example #15
Source File: EsAbstractBehavior.java    From fess with Apache License 2.0 5 votes vote down vote up
@Override
protected int delegateInsert(final Entity entity, final InsertOption<? extends ConditionBean> option) {
    final EsAbstractEntity esEntity = (EsAbstractEntity) entity;
    IndexRequestBuilder builder = createInsertRequest(esEntity);

    final IndexResponse response = builder.execute().actionGet(indexTimeout);
    esEntity.asDocMeta().id(response.getId());
    return response.getResult() == Result.CREATED ? 1 : 0;
}
 
Example #16
Source File: SearchHelper.java    From fess with Apache License 2.0 5 votes vote down vote up
public boolean update(final String id, final Consumer<UpdateRequestBuilder> builderLambda) {
    try {
        final FessConfig fessConfig = ComponentUtil.getFessConfig();
        final UpdateRequestBuilder builder =
                ComponentUtil.getFessEsClient().prepareUpdate().setIndex(fessConfig.getIndexDocumentUpdateIndex()).setId(id);
        builderLambda.accept(builder);
        final UpdateResponse response = builder.execute().actionGet(fessConfig.getIndexIndexTimeout());
        return response.getResult() == Result.CREATED || response.getResult() == Result.UPDATED;
    } catch (final ElasticsearchException e) {
        throw new FessEsClientException("Failed to update doc  " + id, e);
    }
}
 
Example #17
Source File: ElasticsearchClusterRunner.java    From elasticsearch-cluster-runner with Apache License 2.0 5 votes vote down vote up
public DeleteResponse delete(final String index, final String id,
        final BuilderCallback<DeleteRequestBuilder> builder) {
    final DeleteResponse actionGet = builder.apply(client().prepareDelete().setIndex(index).setId(id)).execute().actionGet();
    if (actionGet.getResult() != Result.DELETED) {
        onFailure("Failed to delete " + id + " from " + index + ".", actionGet);
    }
    return actionGet;
}
 
Example #18
Source File: ElasticsearchClusterRunner.java    From elasticsearch-cluster-runner with Apache License 2.0 5 votes vote down vote up
@Deprecated
public DeleteResponse delete(final String index, final String type, final String id,
        final BuilderCallback<DeleteRequestBuilder> builder) {
    final DeleteResponse actionGet = builder.apply(client().prepareDelete(index, type, id)).execute().actionGet();
    if (actionGet.getResult() != Result.DELETED) {
        onFailure("Failed to delete " + id + " from " + index + "/" + type + ".", actionGet);
    }
    return actionGet;
}
 
Example #19
Source File: ElasticsearchClusterRunner.java    From elasticsearch-cluster-runner with Apache License 2.0 5 votes vote down vote up
public IndexResponse insert(final String index, final String id,
        final BuilderCallback<IndexRequestBuilder> builder) {
    final IndexResponse actionGet = builder.apply(client().prepareIndex().setIndex(index).setId(id)).execute().actionGet();
    if (actionGet.getResult() != Result.CREATED) {
        onFailure("Failed to insert " + id + " into " + index + ".", actionGet);
    }
    return actionGet;
}
 
Example #20
Source File: LegacyDetectorRepositoryImplTest.java    From adaptive-alerting with Apache License 2.0 5 votes vote down vote up
@Test(expected = RecordNotFoundException.class)
public void updateDetector_illegal_args() {
    val updateResponse = mock(UpdateResponse.class);
    val result = updateResponse.getResult();
    val mom = ObjectMother.instance();
    val document = mom.buildDetectorDocument();
    document.setUuid(UUID.randomUUID());
    Mockito.when(result).thenReturn(DocWriteResponse.Result.NOT_FOUND);
    Mockito.when(elasticsearchUtil.checkNullResponse(result)).thenReturn(true);
    repoUnderTest.updateDetector("aeb4d849-847a-45c0-8312-dc0fcf22b639", document);
}
 
Example #21
Source File: DynamicRankingPluginTest.java    From elasticsearch-dynarank with Apache License 2.0 5 votes vote down vote up
@Test
public void skipReorder_scrollSearch() throws Exception {

    assertThat(1, is(runner.getNodeSize()));
    final Client client = runner.client();

    final String index = "sample";
    final String type = "_doc";
    runner.createIndex(index,
            Settings.builder().put(DynamicRanker.SETTING_INDEX_DYNARANK_REORDER_SIZE.getKey(), 100)
                    .put(DynamicRanker.SETTING_INDEX_DYNARANK_SCRIPT.getKey(),
                            "Arrays.sort(hits, (s1,s2)-> s2.getSourceAsMap().get(\"counter\") - s1.getSourceAsMap().get(\"counter\"))")
                    .put(DynamicRanker.SETTING_INDEX_DYNARANK_PARAMS.getKey() + "foo", "bar").build());

    for (int i = 1; i <= 1000; i++) {
        final IndexResponse indexResponse1 = runner.insert(index, type, String.valueOf(i),
                "{\"id\":\"" + i + "\",\"msg\":\"test " + i + "\",\"counter\":" + i + "}");
        assertEquals(Result.CREATED, indexResponse1.getResult());
    }

    {
        final SearchResponse searchResponse =
                client.prepareSearch(index).setQuery(QueryBuilders.matchAllQuery()).addSort("counter", SortOrder.ASC)
                        //.putHeader("_rerank", false)
                        .execute().actionGet();
        final SearchHits hits = searchResponse.getHits();
        assertEquals(1000, hits.getTotalHits().value);
        assertEquals(10, hits.getHits().length);
        assertEquals("1", hits.getHits()[0].getId());
        assertEquals("10", hits.getHits()[9].getId());
    }

}
 
Example #22
Source File: DynamicRankingPluginTest.java    From elasticsearch-dynarank with Apache License 2.0 5 votes vote down vote up
@Test
public void skipReorder() throws Exception {

    assertThat(1, is(runner.getNodeSize()));
    final Client client = runner.client();

    final String index = "sample";
    final String type = "_doc";
    runner.createIndex(index,
            Settings.builder().put(DynamicRanker.SETTING_INDEX_DYNARANK_REORDER_SIZE.getKey(), 100)
                    .put(DynamicRanker.SETTING_INDEX_DYNARANK_SCRIPT.getKey(),
                            "searchHits.sort {s1, s2 -> s2.getSourceAsMap().get('counter') - s1.getSourceAsMap().get('counter')} as org.elasticsearch.search.SearchHit[]")
                    .put(DynamicRanker.SETTING_INDEX_DYNARANK_PARAMS.getKey() + "foo", "bar").build());

    for (int i = 1; i <= 1000; i++) {
        final IndexResponse indexResponse1 = runner.insert(index, type, String.valueOf(i),
                "{\"id\":\"" + i + "\",\"msg\":\"test " + i + "\",\"counter\":" + i + "}");
        assertEquals(Result.CREATED, indexResponse1.getResult());
    }

    {
        final SearchResponse searchResponse = client.prepareSearch(index).setQuery(QueryBuilders.matchAllQuery())
                .addSort("counter", SortOrder.ASC).setScroll("1m").execute().actionGet();
        final SearchHits hits = searchResponse.getHits();
        assertEquals(1000, hits.getTotalHits().value);
        assertEquals(10, hits.getHits().length);
        assertEquals("1", hits.getHits()[0].getId());
        assertEquals("10", hits.getHits()[9].getId());
    }

}
 
Example #23
Source File: DynamicRankingPluginTest.java    From elasticsearch-dynarank with Apache License 2.0 5 votes vote down vote up
private void insertTestData(final String index, final String type, final int id, final String msg, final String category) {
    assertEquals(Result.CREATED,
            runner.insert(index, type, String.valueOf(id),
                    "{\"id\":\"" + id + "\",\"msg\":\"" + msg + "\",\"category\":\"" + category + "\",\"order\":" + id + "}")
                    .getResult());

}
 
Example #24
Source File: ElasticsearchIntegrationTest.java    From openshift-elasticsearch-plugin with Apache License 2.0 5 votes vote down vote up
protected void givenDocumentIsIndexed(String index, String type, String id, XContentBuilder content)
        throws Exception {
    ThreadContext threadContext = esNode1.client().threadPool().getThreadContext();
    try (StoredContext cxt = threadContext.stashContext()) {
        threadContext.putHeader(ConfigConstants.SG_CONF_REQUEST_HEADER, "true");
        IndexResponse response = esNode1.client().prepareIndex(index, type, id)
                .setSource(content)
                .setRefreshPolicy(RefreshPolicy.IMMEDIATE)
                .execute()
                .get();
        if(!Result.CREATED.equals(response.getResult())){
            throw new RuntimeException("Test setup failed trying to index a document.  Exp. CREATED but was: " + response.getResult());
        }
    }
}
 
Example #25
Source File: ElasticClientHelper.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
public boolean indexAlarmConfigDocument(String indexName, AlarmConfigMessage alarmConfigMessage) {
    IndexRequest indexRequest = new IndexRequest(indexName.toLowerCase(), "alarm_config");
    try {
        indexRequest.source(alarmConfigMessage.sourceMap());
        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
        return indexResponse.getResult().equals(Result.CREATED);
    } catch (IOException e) {
        logger.log(Level.SEVERE, "failed to log message " + alarmConfigMessage + " to index " + indexName, e);
        return false;
    }
}
 
Example #26
Source File: ElasticClientHelper.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
public boolean indexAlarmCmdDocument(String indexName, AlarmCommandMessage alarmCommandMessage) {
    IndexRequest indexRequest = new IndexRequest(indexName.toLowerCase(), "alarm_cmd");
    try {
        indexRequest.source(alarmCommandMessage.sourceMap());
        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
        return indexResponse.getResult().equals(Result.CREATED);
    } catch (IOException e) {
        logger.log(Level.SEVERE, "failed to log message " + alarmCommandMessage + " to index " + indexName, e);
        return false;
    }
}
 
Example #27
Source File: ElasticClientHelper.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
public boolean indexAlarmStateDocument(String indexName, AlarmStateMessage alarmStateMessage) {
    IndexRequest indexRequest = new IndexRequest(indexName.toLowerCase(), "alarm");
    try {
        indexRequest.source(alarmStateMessage.sourceMap());
        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
        return indexResponse.getResult().equals(Result.CREATED);
    } catch (IOException e) {
        logger.log(Level.SEVERE, "failed to log message " + alarmStateMessage + " to index " + indexName, e);
        return false;
    }
}
 
Example #28
Source File: LegacyDetectorRepositoryImplTest.java    From adaptive-alerting with Apache License 2.0 5 votes vote down vote up
@Test(expected = RecordNotFoundException.class)
public void toggleDetector_illegal_args() {
    val updateResponse = mock(UpdateResponse.class);
    val result = updateResponse.getResult();
    Mockito.when(result).thenReturn(DocWriteResponse.Result.NOT_FOUND);
    Mockito.when(elasticsearchUtil.checkNullResponse(result)).thenReturn(true);
    repoUnderTest.toggleDetector("aeb4d849-847a-45c0-8312-dc0fcf22b639", true);
}
 
Example #29
Source File: LegacyDetectorRepositoryImplTest.java    From adaptive-alerting with Apache License 2.0 5 votes vote down vote up
@Test(expected = RecordNotFoundException.class)
public void trustDetector_illegal_args() {
    val updateResponse = mock(UpdateResponse.class);
    val result = updateResponse.getResult();
    Mockito.when(result).thenReturn(DocWriteResponse.Result.NOT_FOUND);
    Mockito.when(elasticsearchUtil.checkNullResponse(result)).thenReturn(true);
    repoUnderTest.trustDetector("aeb4d849-847a-45c0-8312-dc0fcf22b639", true);
}
 
Example #30
Source File: DetectorMappingRepositoryImplTest.java    From adaptive-alerting with Apache License 2.0 5 votes vote down vote up
@Test(expected = RecordNotFoundException.class)
public void deleteDetectorMapping_illegal_args() throws Exception {
    val deleteResponse = mockDeleteResponse("1");
    Mockito.when(legacyElasticSearchClient.delete(any(DeleteRequest.class), eq(RequestOptions.DEFAULT))).thenReturn(deleteResponse);
    Mockito.when(deleteResponse.getResult()).thenReturn(DocWriteResponse.Result.NOT_FOUND);
    Mockito.when(elasticsearchUtil.checkNullResponse(deleteResponse.getResult())).thenReturn(true);
    repoUnderTest.deleteDetectorMapping("1");
}