@Override public void updateById(String index, String type, String id, String jsonStr) { transportClient.prepareUpdate(index, type,id) .setDoc(jsonStr, XContentType.JSON) .get(); }
/** * 更新数据 * ElasticSearch提供了根据索引名称,类别,文档ID来修改数据,修改的设置数据可以是Map,Json串,自带工具。我们实际开发一般用Json。 */ @Test public void testUpdate(){ JSONObject jsonObject=new JSONObject(); jsonObject.put("user", "锋哥"); jsonObject.put("postDate", "1989-11-11"); jsonObject.put("message", "学习Elasticsearch"); UpdateResponse response = client.prepareUpdate("twitter", "tweet", "1").setDoc(jsonObject.toString(),XContentType.JSON).get(); System.out.println("索引名称:"+response.getIndex()); System.out.println("类型:"+response.getType()); System.out.println("文档ID:"+response.getId()); System.out.println("当前实例状态:"+response.status()); }
/** * 修改 * * @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()); }
/** * 更新一条索引 (overwrite exists) * * @param index * @param type * @param id * @param source * @return */ public static UpdateResponse prepareUpdate(String index, String type, String id, Map source) { UpdateResponse response = getInstance().prepareUpdate(index, type, id).setDoc(source).get(); return response; }
@SuppressWarnings("unchecked") private void addUuidToMetadataIfNeeded(String uuid) throws ElasticsearchException { GetResponse resp = client .prepareGet(settings.getIndexId(), MetadataDataMapping.METADATA_TYPE_NAME, MetadataDataMapping.METADATA_ROW_ID) .setOperationThreaded(false).get(); Object retValues = resp.getSourceAsMap().get(MetadataDataMapping.METADATA_UUIDS_FIELD.getName()); List<String> values; if (retValues instanceof String) { values = new LinkedList<>(); values.add((String) retValues); } else if (retValues instanceof List<?>) { values = (List<String>) retValues; } else { throw new ConfigurationError("Invalid %s field type %s should have String or java.util.Collection<String>", MetadataDataMapping.METADATA_UUIDS_FIELD, retValues.getClass()); } // add new uuid if needed if (!values.stream().anyMatch(m -> m.equals(uuid))) { Map<String, Object> uuids = new HashMap<>(); values.add(uuid); uuids.put(MetadataDataMapping.METADATA_UUIDS_FIELD.getName(), values); uuids.put(MetadataDataMapping.METADATA_UPDATE_TIME_FIELD.getName(), Calendar.getInstance(DateTimeZone.UTC .toTimeZone())); client.prepareUpdate(settings.getIndexId(), MetadataDataMapping.METADATA_TYPE_NAME, "1").setDoc(uuids).get(); logger.info("UUID {} is added to the {} type", uuid, MetadataDataMapping.METADATA_TYPE_NAME); } }
@Override public void indexOne(long id) { if (!existsIndex()) { logger .debug("Can't delete {} element with id {} as the index doesn't exist !", this.configuration.getAlias(), id); return; } try { DTO dto = this.service.getOne(id); if (dto != null) { this.prepareIndexRequest(this.configuration.getAlias(), dto).get(); } } catch (Exception e) { logger.error("Can't index {} element with id {}", this.configuration.getAlias(), id, e); } }
/** * Helper method to remove fields from source. This method will generate a ES update request. Retries on conflict. * * @param element Element that can be mapped to an ES document * @param fields fields to remove */ private void removeFieldsFromDocument(Element element, Collection<String> fields) { Map<String, Object> params = Maps.newHashMap(); int i = 0; StringBuilder script = new StringBuilder(); for (String field : fields) { String fieldName = "fieldName" + (i++); script.append("ctx._source.remove(").append(fieldName).append(");"); params.put(fieldName, field); } getClient().prepareUpdate() .setIndex(getIndexName(element)) .setId(element.getId()) .setType(ELEMENT_TYPE) .setScript( new Script( script.toString(), ScriptService.ScriptType.INLINE, null, params ) ) .setRetryOnConflict(MAX_RETRIES) .get(); }
response = client .prepareUpdate(indexFormated, indexFormated, documentId) .setDoc(convertObjectToJsonString(source), XContentType.JSON).get();
/** * {@inheritDoc} */ @Override public void softDelete(final String type, final String id, final MetacatRequestContext metacatRequestContext) { try { RETRY_ES_PUBLISH.call(() -> { final XContentBuilder builder = XContentFactory.contentBuilder(contentType); builder.startObject().field(ElasticSearchDoc.Field.DELETED, true) .field(ElasticSearchDoc.Field.TIMESTAMP, java.time.Instant.now().toEpochMilli()) .field(ElasticSearchDoc.Field.USER, metacatRequestContext.getUserName()).endObject(); client.prepareUpdate(esIndex, type, id) .setRetryOnConflict(NO_OF_CONFLICT_RETRIES).setDoc(builder).get(esCallTimeout); ensureMigrationByCopy(type, Collections.singletonList(id)); return null; }); } catch (Exception e) { handleException("ElasticSearchUtil.softDelete", type, id, e, Metrics.CounterElasticSearchDelete.getMetricName()); } }
@Override public void markElementHidden(Graph graph, Element element, Visibility visibility, Authorizations authorizations) { try { String hiddenVisibilityPropertyName = addVisibilityToPropertyName(graph, HIDDEN_VERTEX_FIELD_NAME, visibility); if (!isPropertyInIndex(graph, hiddenVisibilityPropertyName)) { String indexName = getIndexName(element); IndexInfo indexInfo = ensureIndexCreatedAndInitialized(graph, indexName); addPropertyToIndex(graph, indexInfo, hiddenVisibilityPropertyName, visibility, Boolean.class, false); } XContentBuilder jsonBuilder = XContentFactory.jsonBuilder().startObject(); jsonBuilder.field(hiddenVisibilityPropertyName, true); jsonBuilder.endObject(); getClient() .prepareUpdate(getIndexName(element), ELEMENT_TYPE, element.getId()) .setDoc(jsonBuilder) .setRetryOnConflict(MAX_RETRIES) .get(); } catch (IOException e) { throw new VertexiumException("Could not mark element hidden", e); } }
@Override public void alterElementVisibility( Graph graph, Element element, Visibility oldVisibility, Visibility newVisibility, Authorizations authorizations ) { String oldFieldName = deflatePropertyName(graph, ELEMENT_TYPE_FIELD_NAME, oldVisibility); Script script = new Script( "ctx._source.remove(oldFieldName);", ScriptService.ScriptType.INLINE, null, ImmutableMap.<String, Object>of("oldFieldName", oldFieldName) ); getClient().prepareUpdate() .setIndex(getIndexName(element)) .setId(element.getId()) .setType(ELEMENT_TYPE) .setScript(script) .get(); addElement(graph, element, authorizations); }
@Override public void markPropertyHidden(Graph graph, Element element, Property property, Visibility visibility, Authorizations authorizations) { try { String hiddenVisibilityPropertyName = addVisibilityToPropertyName(graph, HIDDEN_PROPERTY_FIELD_NAME, visibility); String indexName = getIndexName(element); if (!isPropertyInIndex(graph, HIDDEN_PROPERTY_FIELD_NAME, visibility)) { IndexInfo indexInfo = ensureIndexCreatedAndInitialized(indexName); addPropertyToIndex(graph, indexInfo, hiddenVisibilityPropertyName, visibility, Boolean.class, false, false, false); } XContentBuilder jsonBuilder = XContentFactory.jsonBuilder().startObject(); jsonBuilder.field(hiddenVisibilityPropertyName, true); jsonBuilder.endObject(); getClient() .prepareUpdate(indexName, getIdStrategy().getType(), getIdStrategy().createElementDocId(element)) .setDoc(jsonBuilder) .setRetryOnConflict(MAX_RETRIES) .get(); getIndexRefreshTracker().pushChange(indexName); } catch (IOException e) { throw new VertexiumException("Could not mark element hidden", e); } }
@Override public void markPropertyHidden(Graph graph, Element element, Property property, Visibility visibility, Authorizations authorizations) { try { String hiddenVisibilityPropertyName = addVisibilityToPropertyName(graph, HIDDEN_PROPERTY_FIELD_NAME, visibility); String indexName = getIndexName(element); if (!isPropertyInIndex(graph, HIDDEN_PROPERTY_FIELD_NAME, visibility)) { IndexInfo indexInfo = ensureIndexCreatedAndInitialized(indexName); addPropertyToIndex(graph, indexInfo, hiddenVisibilityPropertyName, visibility, Boolean.class, false, false, false); } XContentBuilder jsonBuilder = XContentFactory.jsonBuilder().startObject(); jsonBuilder.field(hiddenVisibilityPropertyName, true); jsonBuilder.endObject(); getClient() .prepareUpdate(indexName, getIdStrategy().getType(), getIdStrategy().createElementDocId(element)) .setDoc(jsonBuilder) .setRetryOnConflict(MAX_RETRIES) .get(); getIndexRefreshTracker().pushChange(indexName); } catch (IOException e) { throw new VertexiumException("Could not mark element hidden", e); } }
@Override public void markElementHidden(Graph graph, Element element, Visibility visibility, Authorizations authorizations) { try { String hiddenVisibilityPropertyName = addVisibilityToPropertyName(graph, HIDDEN_VERTEX_FIELD_NAME, visibility); String indexName = getIndexName(element); if (!isPropertyInIndex(graph, HIDDEN_VERTEX_FIELD_NAME, visibility)) { IndexInfo indexInfo = ensureIndexCreatedAndInitialized(indexName); addPropertyToIndex(graph, indexInfo, hiddenVisibilityPropertyName, visibility, Boolean.class, false, false, false); } XContentBuilder jsonBuilder = XContentFactory.jsonBuilder().startObject(); jsonBuilder.field(hiddenVisibilityPropertyName, true); jsonBuilder.endObject(); getIndexRefreshTracker().pushChange(indexName); getClient() .prepareUpdate(indexName, getIdStrategy().getType(), getIdStrategy().createElementDocId(element)) .setDoc(jsonBuilder) .setRetryOnConflict(MAX_RETRIES) .get(); getIndexRefreshTracker().pushChange(indexName); } catch (IOException e) { throw new VertexiumException("Could not mark element hidden", e); } }
@Override public void markElementHidden(Graph graph, Element element, Visibility visibility, Authorizations authorizations) { try { String hiddenVisibilityPropertyName = addVisibilityToPropertyName(graph, HIDDEN_VERTEX_FIELD_NAME, visibility); String indexName = getIndexName(element); if (!isPropertyInIndex(graph, HIDDEN_VERTEX_FIELD_NAME, visibility)) { IndexInfo indexInfo = ensureIndexCreatedAndInitialized(indexName); addPropertyToIndex(graph, indexInfo, hiddenVisibilityPropertyName, visibility, Boolean.class, false, false, false); } XContentBuilder jsonBuilder = XContentFactory.jsonBuilder().startObject(); jsonBuilder.field(hiddenVisibilityPropertyName, true); jsonBuilder.endObject(); getIndexRefreshTracker().pushChange(indexName); getClient() .prepareUpdate(indexName, getIdStrategy().getType(), getIdStrategy().createElementDocId(element)) .setDoc(jsonBuilder) .setRetryOnConflict(MAX_RETRIES) .get(); getIndexRefreshTracker().pushChange(indexName); } catch (IOException e) { throw new VertexiumException("Could not mark element hidden", e); } }