org.elasticsearch.action.update.UpdateResponse Java Examples

The following examples show how to use org.elasticsearch.action.update.UpdateResponse. 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: ElasticsearchTransactionManager.java    From jstarcraft-core with Apache License 2.0 7 votes vote down vote up
@Override
protected void unlock(TransactionDefinition definition) {
    // 尝试解锁
    String key = definition.getName();
    Long value = definition.getMost().toEpochMilli();
    Map<String, Object> document = new HashMap<>();
    document.put(NAME, key);
    document.put(MOST, value);
    document.put(NOW, Instant.now().toEpochMilli());
    UpdateRequest request = new UpdateRequest().index(index).type(type)

            .id(key)

            .script(new Script(ScriptType.INLINE, SCRIPT, UNLOCK_SCRIPT, document));
    try {
        UpdateResponse response = elastic.update(request, RequestOptions.DEFAULT);
        if (response.getResult() == DocWriteResponse.Result.NOOP) {
            throw new TransactionUnlockException();
        }
    } catch (Exception exception) {
        throw new TransactionUnlockException(exception);
    }
}
 
Example #2
Source File: DefaultElasticSearchService.java    From vertx-elasticsearch-service with Apache License 2.0 6 votes vote down vote up
@Override
public void update(String index, String type, String id, UpdateOptions options, Handler<AsyncResult<com.hubrick.vertx.elasticsearch.model.UpdateResponse>> resultHandler) {

    final UpdateRequestBuilder builder = client.prepareUpdate(index, type, id);
    populateUpdateRequestBuilder(builder, options);

    builder.execute(new ActionListener<UpdateResponse>() {
        @Override
        public void onResponse(UpdateResponse updateResponse) {
            resultHandler.handle(Future.succeededFuture(mapToUpdateResponse(updateResponse)));
        }

        @Override
        public void onFailure(Exception e) {
            handleFailure(resultHandler, e);
        }
    });

}
 
Example #3
Source File: BulkItemResponse.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public void writeTo(StreamOutput out) throws IOException {
    out.writeVInt(id);
    out.writeString(opType);

    if (response == null) {
        out.writeByte((byte) 2);
    } else {
        if (response instanceof IndexResponse) {
            out.writeByte((byte) 0);
        } else if (response instanceof DeleteResponse) {
            out.writeByte((byte) 1);
        } else if (response instanceof UpdateResponse) {
            out.writeByte((byte) 3); // make 3 instead of 2, because 2 is already in use for 'no responses'
        }
        response.writeTo(out);
    }
    if (failure == null) {
        out.writeBoolean(false);
    } else {
        out.writeBoolean(true);
        failure.writeTo(out);
    }
}
 
Example #4
Source File: ElasticsearchHighRestFactory.java    From database-transform-tool with Apache License 2.0 6 votes vote down vote up
public String upsert(String index,String type,String id,Object json){
		try {
			if(xclient==null){
				init();
			}
//			IndexRequest indexRequest = new IndexRequest(index, type, id).source(json,XContentType.JSON);
//			UpdateRequest updateRequest = new UpdateRequest(index, type, id).doc(json,XContentType.JSON).upsert(indexRequest);
			UpdateRequest request = new UpdateRequest(index, type, id);
			request.upsert(JSON.parseObject(JSON.toJSONString(json)),XContentType.JSON);
			UpdateResponse response = xclient.update(request);
			return response.toString();
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
 
Example #5
Source File: ElasticSearchRestDAOV5.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Override
public void updateWorkflow(String workflowInstanceId, String[] keys, Object[] values) {
    if (keys.length != values.length) {
        throw new ApplicationException(ApplicationException.Code.INVALID_INPUT, "Number of keys and values do not match");
    }

    long startTime = Instant.now().toEpochMilli();
    UpdateRequest request = new UpdateRequest(indexName, WORKFLOW_DOC_TYPE, workflowInstanceId);
    Map<String, Object> source = IntStream.range(0, keys.length).boxed()
            .collect(Collectors.toMap(i -> keys[i], i -> values[i]));
    request.doc(source);

    logger.debug("Updating workflow {} with {}", workflowInstanceId, source);

    new RetryUtil<UpdateResponse>().retryOnException(() -> {
        try {
            return elasticSearchClient.update(request);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }, null, null, RETRY_COUNT, "Updating workflow document: " + workflowInstanceId, "updateWorkflow");
    long endTime = Instant.now().toEpochMilli();
    logger.debug("Time taken {} for updating workflow: {}", endTime - startTime, workflowInstanceId);
    Monitors.recordESIndexTime("update_workflow", WORKFLOW_DOC_TYPE, endTime - startTime);
    Monitors.recordWorkerQueueSize("indexQueue", ((ThreadPoolExecutor) executorService).getQueue().size());
}
 
Example #6
Source File: PluginClient.java    From openshift-elasticsearch-plugin with Apache License 2.0 6 votes vote down vote up
public UpdateResponse updateDocument(String index, String type, String id, String source) {
    return execute(new Callable<UpdateResponse>() {

        @Override
        public UpdateResponse call() throws Exception {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Updating Document: '{}/{}/{}' source: '{}'", index, type, id, source);
            }
            UpdateResponse response = client.prepareUpdate(index, type, id).setDoc(source, XContentType.JSON)
                    .setDocAsUpsert(true).get();

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Document Updated: '{}'", response.status());
            }
            return response;
        }
    });
}
 
Example #7
Source File: UpdateApiMain.java    From elasticsearch-pool with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
        try{
            RestHighLevelClient client = HighLevelClient.getInstance();
            UpdateRequest updateRequest = new UpdateRequest("jingma2_20180716", "testlog", "1");
            updateRequest.doc(buildIndexData());//传递Map结构数据
            //updateRequest.doc(jsonString, XContentType.JSON);//传递json字符串

//            updateRequest.version(1);//设置待更新文档的版本,防止高并发下误更新
//            updateRequest.upsert(buildIndexData());//没有文档时插入该文档
//            updateRequest.upsert(jsonString, XContentType.JSON);

            UpdateResponse updateResponse = client.update(updateRequest);
                    System.out.println(updateResponse);
        }finally{
            HighLevelClient.close();
        }
    }
 
Example #8
Source File: ElasticsearchClient.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 6 votes vote down vote up
private boolean writeMapInternal(String indexName, String typeName, String id, final Map<String, Object> jsonMap) {
    long start = System.currentTimeMillis();
    // get the version number out of the json, if any is given
    Long version = (Long) jsonMap.remove("_version");
    // put this to the index
    UpdateResponse r = elasticsearchClient
        .prepareUpdate(indexName, typeName, id)
        .setDoc(jsonMap)
        .setUpsert(jsonMap)
        //.setVersion(version == null ? 1 : version.longValue())
        //.setVersionType(VersionType.EXTERNAL_GTE)
        .execute()
        .actionGet();
    if (version != null) jsonMap.put("_version", version); // to prevent side effects
    // documentation about the versioning is available at
    // https://www.elastic.co/blog/elasticsearch-versioning-support
    // TODO: error handling
    boolean created = r != null && r.status() == RestStatus.CREATED; // true means created, false means updated
    long duration = Math.max(1, System.currentTimeMillis() - start);
    Data.logger.info("ElasticsearchClient write entry to index " + indexName + ": " + (created ? "created":"updated") + ", " + duration + " ms");
    return created;
}
 
Example #9
Source File: ElasticSearchServer.java    From vind with Apache License 2.0 6 votes vote down vote up
@Override
public boolean execute(Update update, DocumentFactory factory) {
    try {
        log.warn("Update script builder does not check for script injection. Ensure values provided are script safe.");
        final StopWatch elapsedTime = StopWatch.createStarted();
        elasticClientLogger.debug(">>> delete({})", update);
        final PainlessScript.ScriptBuilder updateScript = ElasticQueryBuilder.buildUpdateScript(update.getOptions(), factory, update.getUpdateContext());
        final UpdateResponse response = elasticSearchClient.update(update.getId(), updateScript);
        elapsedTime.stop();
        return true;
    } catch (ElasticsearchException | IOException e) {
        log.error("Cannot update document {}: {}", update.getId(), e.getMessage() , e);
        throw new SearchServerException(
                String.format("Cannot update document %s: %s", update.getId(), e.getMessage()), e);
    }
}
 
Example #10
Source File: ElasticSearcher.java    From jpress with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void updateArticle(Article article) {
    UpdateRequest updateRequest = new UpdateRequest(index, type, article.getId().toString());
    Map<String, Object> map = new HashMap<>();
    map.putAll(CPI.getAttrs(article));
    updateRequest.doc(map);

    try {
        UpdateResponse response = client.update(updateRequest, RequestOptions.DEFAULT);
        if (LogKit.isDebugEnabled()) {
            LogKit.debug(response.toString());
        }
    } catch (Exception e) {
        LOG.error(e.toString(), e);
    }
}
 
Example #11
Source File: ElasticSearcher.java    From jpress with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void updateProduct(Product product) {
    UpdateRequest updateRequest = new UpdateRequest(index, type, product.getId().toString());
    Map<String, Object> map = new HashMap<>();
    map.putAll(CPI.getAttrs(product));
    updateRequest.doc(map);

    try {
        UpdateResponse response = client.update(updateRequest, RequestOptions.DEFAULT);
        if (LogKit.isDebugEnabled()) {
            LogKit.debug(response.toString());
        }
    } catch (Exception e) {
        LOG.error(e.toString(), e);
    }
}
 
Example #12
Source File: ElasticsearchClientTransport.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public boolean updateIndex(IndexMetadata indexMetadata, String data) {
  UpdateRequest updateRequest = new UpdateRequest(indexMetadata.getName(), TYPE, indexMetadata.getId());
  updateRequest.doc(data, XContentType.JSON);
  updateRequest.routing(indexMetadata.getId());

  IndexRequest indexRequest = new IndexRequest(indexMetadata.getName(), TYPE, indexMetadata.getId());
  indexRequest.source(data, XContentType.JSON);
  indexRequest.routing(indexMetadata.getId());

  updateRequest.upsert(indexRequest);

  try {
    UpdateResponse updateResponse = client.update(updateRequest).get();
    return updateResponse.status().equals(RestStatus.OK);
  } catch (InterruptedException | ExecutionException e) {
    log.error("Error updating index '{}'.", indexMetadata.getName(), e);
  }

  return false;
}
 
Example #13
Source File: ElasticSearchServiceMapper.java    From vertx-elasticsearch-service with Apache License 2.0 6 votes vote down vote up
public static com.hubrick.vertx.elasticsearch.model.UpdateResponse mapToUpdateResponse(UpdateResponse esUpdateResponse) {
    final com.hubrick.vertx.elasticsearch.model.UpdateResponse updateResponse = new com.hubrick.vertx.elasticsearch.model.UpdateResponse();

    updateResponse.setShards(mapToShards(esUpdateResponse.getShardInfo()));
    updateResponse.setIndex(esUpdateResponse.getIndex());
    updateResponse.setType(esUpdateResponse.getType());
    updateResponse.setId(esUpdateResponse.getId());
    updateResponse.setVersion(esUpdateResponse.getVersion());
    updateResponse.setCreated(esUpdateResponse.status().equals(RestStatus.CREATED));

    if (esUpdateResponse.getGetResult() != null) {
        updateResponse.setResult(mapToGetResult(esUpdateResponse.getGetResult()));
    }

    return updateResponse;
}
 
Example #14
Source File: ESNestedSearchService.java    From search-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
/**
 * 更新操作
 *
 * @param esObject es通用更新请求参数
 * @return <code>true</code> 保存或更新成功; 否则更新失败
 */
public SearchBaseResult<Boolean> update(UpdateESObject esObject) {
    final UpdateRequestBuilder updateRequest = esObject.nestedUpdate() ? getNestedListUpdateRequest(esObject)
            : getUpdateRequest(esObject);
    SearchLogger.log(updateRequest);
    try {
        updateRequest.setDetectNoop(false);
        if (esObject.isRefresh()) {
            updateRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);
        }
        UpdateResponse updateResponse = updateRequest.execute().get();
        SearchLogger.log(updateResponse);
        final DocWriteResponse.Result result = updateResponse.getResult();
        return SearchBaseResult.success(DocWriteResponse.Result.UPDATED == result, Boolean.class);
    } catch (Exception ex) {
        SearchLogger.error("update", ex);
        final String message = ex.getMessage();
        if (message != null && message.contains("document missing")) {
            return SearchBaseResult.faild(ESErrorCode.DOC_NOT_EXIST_ERROR_CODE, "更新文档不存在");
        }
        return SearchBaseResult.faild(ESErrorCode.ELASTIC_ERROR_CODE, "esMsg:" + message);
    }
}
 
Example #15
Source File: ElasticsearchClientRest.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public boolean updateIndex(IndexMetadata indexMetadata, String data) {
  UpdateRequest updateRequest = new UpdateRequest(indexMetadata.getName(), TYPE, indexMetadata.getId());
  updateRequest.doc(data, XContentType.JSON);
  updateRequest.routing(indexMetadata.getId());

  IndexRequest indexRequest = new IndexRequest(indexMetadata.getName(), TYPE);
  if (indexMetadata.getId() != null && !indexMetadata.getId().isEmpty()) {
    indexRequest.id(indexMetadata.getId());
  }
  indexRequest.source(data, XContentType.JSON);

  updateRequest.upsert(indexRequest);

  try {
    UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
    return updateResponse.status().equals(RestStatus.OK);
  } catch (IOException e) {
    log.error("Error updating index '{}'.", indexMetadata.getName(), e);
  }
  return false;
}
 
Example #16
Source File: BaseDemo.java    From Elasticsearch-Tutorial-zh-CN with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 修改
 *
 * @param transportClient
 * @throws IOException
 */
private static void update(TransportClient transportClient) throws IOException {
	UpdateResponse updateResponse = transportClient.prepareUpdate("product_index", "product", "1")
			.setDoc(XContentFactory.jsonBuilder()
					.startObject()
					.field("product_name", "飞利浦电动牙刷 HX6700 促销优惠")
					.endObject())
			.get();
	logger.info("--------------------------------:" + updateResponse.getResult());

}
 
Example #17
Source File: TestTransportClient.java    From jframe with Apache License 2.0 5 votes vote down vote up
public void testUpdate() throws Exception {
    UpdateRequest updateRequest = new UpdateRequest();
    updateRequest.index("index");
    updateRequest.type("type");
    updateRequest.id("1");
    updateRequest.doc(XContentFactory.jsonBuilder().startObject().field("gender", "male").endObject());
    UpdateResponse response = client.update(updateRequest).get();
    System.out.println(response.toString());

    client.prepareUpdate("ttl", "doc", "1").setScript(new Script("ctx._source.gender = \"male\"", ScriptService.ScriptType.INLINE, null, null))
            .get();

    client.prepareUpdate("ttl", "doc", "1").setDoc(XContentFactory.jsonBuilder().startObject().field("gender", "male").endObject()).get();
}
 
Example #18
Source File: ElasticSearchDAOV5.java    From conductor with Apache License 2.0 5 votes vote down vote up
@Override
public void indexWorkflow(Workflow workflow) {
    try {
        long startTime = Instant.now().toEpochMilli();
        String id = workflow.getWorkflowId();
        WorkflowSummary summary = new WorkflowSummary(workflow);
        byte[] doc = objectMapper.writeValueAsBytes(summary);

        UpdateRequest request = new UpdateRequest(indexName, WORKFLOW_DOC_TYPE, id);
        request.doc(doc, XContentType.JSON);
        request.upsert(doc, XContentType.JSON);
        request.retryOnConflict(5);

        new RetryUtil<UpdateResponse>().retryOnException(
            () -> elasticSearchClient.update(request).actionGet(),
            null,
            null,
            RETRY_COUNT,
            "Indexing workflow document: " + workflow.getWorkflowId(),
            "indexWorkflow"
        );

        long endTime = Instant.now().toEpochMilli();
        logger.debug("Time taken {} for indexing workflow: {}", endTime - startTime, workflow.getWorkflowId());
        Monitors.recordESIndexTime("index_workflow", WORKFLOW_DOC_TYPE, endTime - startTime);
        Monitors.recordWorkerQueueSize("indexQueue", ((ThreadPoolExecutor) executorService).getQueue().size());
    } catch (Exception e) {
        Monitors.error(className, "indexWorkflow");
        logger.error("Failed to index workflow: {}", workflow.getWorkflowId(), e);
    }
}
 
Example #19
Source File: EsServiceMappingStore.java    From soundwave with Apache License 2.0 5 votes vote down vote up
@Override
public long updateOrInsertServiceMapping(EsServiceMapping serviceMapping) throws Exception {

  UpdateResponse response = this.updateOrInsert(serviceMapping.getName(),
      mapper.writeValueAsBytes(serviceMapping),
      mapper.writeValueAsBytes(serviceMapping));

  return response.isCreated() ? 0 : response.getVersion();
}
 
Example #20
Source File: ElasticSearchRestDAOV6.java    From conductor with Apache License 2.0 5 votes vote down vote up
@Override
public void updateWorkflow(String workflowInstanceId, String[] keys, Object[] values) {
    if (keys.length != values.length) {
        throw new ApplicationException(ApplicationException.Code.INVALID_INPUT,
            "Number of keys and values do not match");
    }

    long startTime = Instant.now().toEpochMilli();
    String docType = StringUtils.isBlank(docTypeOverride) ? WORKFLOW_DOC_TYPE : docTypeOverride;
    UpdateRequest request = new UpdateRequest(workflowIndexName, docType, workflowInstanceId);
    Map<String, Object> source = IntStream.range(0, keys.length).boxed()
        .collect(Collectors.toMap(i -> keys[i], i -> values[i]));
    request.doc(source);

    logger.debug("Updating workflow {} with {}", workflowInstanceId, source);

    new RetryUtil<UpdateResponse>().retryOnException(() -> {
        try {
            return elasticSearchClient.update(request);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }, null, null, RETRY_COUNT, "Updating workflow document: " + workflowInstanceId, "updateWorkflow");
    long endTime = Instant.now().toEpochMilli();
    logger.debug("Time taken {} for updating workflow: {}", endTime - startTime, workflowInstanceId);
    Monitors.recordESIndexTime("update_workflow", WORKFLOW_DOC_TYPE, endTime - startTime);
    Monitors.recordWorkerQueueSize("indexQueue", ((ThreadPoolExecutor) executorService).getQueue().size());
}
 
Example #21
Source File: ElasticSearchDAOV6.java    From conductor with Apache License 2.0 5 votes vote down vote up
@Override
public void indexWorkflow(Workflow workflow) {
    try {
        long startTime = Instant.now().toEpochMilli();
        String id = workflow.getWorkflowId();
        WorkflowSummary summary = new WorkflowSummary(workflow);
        byte[] doc = objectMapper.writeValueAsBytes(summary);
        String docType = StringUtils.isBlank(docTypeOverride) ? WORKFLOW_DOC_TYPE : docTypeOverride;

        UpdateRequest req = buildUpdateRequest(id, doc, workflowIndexName, docType);
        new RetryUtil<UpdateResponse>().retryOnException(
            () -> elasticSearchClient.update(req).actionGet(),
            null,
            null,
            RETRY_COUNT,
            "Indexing workflow document: " + workflow.getWorkflowId(),
            "indexWorkflow"
        );

        long endTime = Instant.now().toEpochMilli();
        LOGGER.debug("Time taken {} for indexing workflow: {}", endTime - startTime, workflow.getWorkflowId());
        Monitors.recordESIndexTime("index_workflow", WORKFLOW_DOC_TYPE, endTime - startTime);
        Monitors.recordWorkerQueueSize("indexQueue", ((ThreadPoolExecutor) executorService).getQueue().size());
    } catch (Exception e) {
        Monitors.error(CLASS_NAME, "indexWorkflow");
        LOGGER.error("Failed to index workflow: {}", workflow.getWorkflowId(), e);
    }
}
 
Example #22
Source File: CommonWebpageDAO.java    From spider with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 更新网页
 *
 * @param webpage 网页
 * @return
 */
public boolean update(Webpage webpage) throws ExecutionException, InterruptedException {
    UpdateRequest updateRequest = new UpdateRequest();
    updateRequest.index(INDEX_NAME);
    updateRequest.type(TYPE_NAME);
    updateRequest.id(webpage.getId());
    updateRequest.doc(gson.toJson(webpage));
    UpdateResponse response = client.update(updateRequest).get();
    return response.getResult() == UpdateResponse.Result.UPDATED;
}
 
Example #23
Source File: ElasticsearchIndexer.java    From datashare with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean tagUntag(Project prj, String documentId, String rootDocument, Script untagScript) throws IOException {
    UpdateRequest update = new UpdateRequest(prj.getId(), esCfg.indexType, documentId).routing(rootDocument);
    update.script(untagScript);
    update.setRefreshPolicy(esCfg.refreshPolicy);
    UpdateResponse updateResponse = client.update(update);
    return updateResponse.status() == RestStatus.OK && updateResponse.getResult() == DocWriteResponse.Result.UPDATED;
}
 
Example #24
Source File: CaseController.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private void update(String indexName) throws IOException {
    UpdateRequest request = new UpdateRequest(indexName, "1");
    Map<String, Object> parameters = singletonMap("title", "c++ programing.");
    Script inline = new Script(ScriptType.INLINE, "painless", "ctx._source.title = params.title", parameters);
    request.script(inline);

    UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
    if (updateResponse.getVersion() != 2) {
        String message = "elasticsearch update data fail.";
        logger.error(message);
        throw new RuntimeException(message);
    }
}
 
Example #25
Source File: ElasticsearchLockProvider.java    From ShedLock with Apache License 2.0 5 votes vote down vote up
@Override
@NonNull
public Optional<SimpleLock> lock(@NonNull LockConfiguration lockConfiguration) {
    try {
        Map<String, Object> lockObject = lockObject(lockConfiguration.getName(),
            lockConfiguration.getLockAtMostUntil(),
            now());
        UpdateRequest ur = new UpdateRequest()
            .index(index)
            .type(type)
            .id(lockConfiguration.getName())
            .script(new Script(ScriptType.INLINE,
                "painless",
                UPDATE_SCRIPT,
                lockObject)
            )
            .upsert(lockObject)
            .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
        UpdateResponse res = highLevelClient.update(ur, RequestOptions.DEFAULT);
        if (res.getResult() != DocWriteResponse.Result.NOOP) {
            return Optional.of(new ElasticsearchSimpleLock(lockConfiguration));
        } else {
            return Optional.empty();
        }
    } catch (IOException | ElasticsearchException e) {
        if (e instanceof ElasticsearchException && ((ElasticsearchException) e).status() == RestStatus.CONFLICT) {
            return Optional.empty();
        } else {
            throw new LockException("Unexpected exception occurred", e);
        }
    }
}
 
Example #26
Source File: AdapterActionFutureActionGetMethodsInterceptor.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private void parseUpdateResponse(UpdateResponse updateResponse, AbstractSpan span) {
    if (TRACE_DSL) {
        String tagValue = updateResponse.toString();
        tagValue = ELASTICSEARCH_DSL_LENGTH_THRESHOLD > 0 ? StringUtil.cut(tagValue, ELASTICSEARCH_DSL_LENGTH_THRESHOLD) : tagValue;
        Tags.DB_STATEMENT.set(span, tagValue);
    }
}
 
Example #27
Source File: EsStore.java    From soundwave with Apache License 2.0 5 votes vote down vote up
protected UpdateResponse updateOrInsert(String id, byte[] updateDoc, byte[] insertDoc)
    throws Exception {
  IndexRequest
      indexRequest =
      new IndexRequest(getIndexName(), getDocTypeName(), id).source(insertDoc);

  UpdateRequest
      updateRequest =
      new UpdateRequest(getIndexName(), getDocTypeName(), id).doc(updateDoc).upsert(indexRequest);
  return esClient.update(updateRequest).actionGet();
}
 
Example #28
Source File: EsBulkResponseSummary.java    From soundwave with Apache License 2.0 5 votes vote down vote up
private String getItemId(BulkItemResponse response) {
  String id = response.getId();
  if (response.getResponse() instanceof UpdateResponse) {
    id = ((UpdateResponse) response.getResponse()).getId();
  } else if (response.getResponse() instanceof IndexResponse) {
    id = ((IndexResponse) response.getResponse()).getId();
  }
  return id;
}
 
Example #29
Source File: BulkItemResponse.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * The version of the action.
 */
public long getVersion() {
    if (failure != null) {
        return -1;
    }
    if (response instanceof IndexResponse) {
        return ((IndexResponse) response).getVersion();
    } else if (response instanceof DeleteResponse) {
        return ((DeleteResponse) response).getVersion();
    } else if (response instanceof UpdateResponse) {
        return ((UpdateResponse) response).getVersion();
    }
    return -1;
}
 
Example #30
Source File: EsInstanceStore.java    From soundwave with Apache License 2.0 5 votes vote down vote up
@Override
public long updateOrInsertInstance(EsInstance instance) throws Exception {
  UpdateResponse
      response =
      this.updateOrInsert(instance.getId(),
          updateMapper.writeValueAsBytes(instance),
          insertMapper.writeValueAsBytes(instance));
  return response.isCreated() ? 0 : response.getVersion();
}