Java Code Examples for org.elasticsearch.action.index.IndexResponse

The following examples show how to use org.elasticsearch.action.index.IndexResponse. These examples are extracted from open source projects. 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
@Override
public String persist(final Event event) {
	String evStr = null;
	try {
		evStr = jsonMapper.writeValueAsString(event);
		final IndexRequest indexRequest = Requests
				.indexRequest(indexNamingStrategy.buildActiveName(event.getSnifferId()))
				.type(getType(event.getSnifferId())).source(evStr);
		final String eventId = clientTpl.executeWithClient(new ClientCallback<IndexResponse>() {
			@Override
			public IndexResponse execute(final Client client) {
				return client.index(indexRequest).actionGet();
			}
		}).getId();
		logger.debug("Persisted event with id: {}", eventId);
		return eventId;
	} catch (final Exception e) {
		throw new DataAccessException("Failed to persiste event: " + evStr, e);
	}
}
 
Example 2
protected void saveAnUpdateConfigs(final Client client, final RestRequest request, final CType cType,
								   final SecurityDynamicConfiguration<?> configuration, OnSucessActionListener<IndexResponse> actionListener) {
	final IndexRequest ir = new IndexRequest(this.opendistroIndex);

	//final String type = "_doc";
	final String id = cType.toLCString();

	configuration.removeStatic();

	try {
		client.index(ir.id(id)
						.setRefreshPolicy(RefreshPolicy.IMMEDIATE)
						.setIfSeqNo(configuration.getSeqNo())
						.setIfPrimaryTerm(configuration.getPrimaryTerm())
						.source(id, XContentHelper.toXContent(configuration, XContentType.JSON, false)),
				new ConfigUpdatingActionListener<IndexResponse>(client, actionListener));
	} catch (IOException e) {
		throw ExceptionsHelper.convertToElastic(e);
	}
}
 
Example 3
Source Project: fess   Source File: EsAbstractBehavior.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected int delegateUpdate(final Entity entity, final UpdateOption<? extends ConditionBean> option) {
    final EsAbstractEntity esEntity = (EsAbstractEntity) entity;
    final IndexRequestBuilder builder = createUpdateRequest(esEntity);

    final IndexResponse response = builder.execute().actionGet(indexTimeout);
    final long seqNo = response.getSeqNo();
    if (seqNo != SequenceNumbers.UNASSIGNED_SEQ_NO) {
        esEntity.asDocMeta().seqNo(seqNo);
    }
    final long primaryTerm = response.getPrimaryTerm();
    if (primaryTerm != SequenceNumbers.UNASSIGNED_PRIMARY_TERM) {
        esEntity.asDocMeta().primaryTerm(primaryTerm);
    }

    return 1;
}
 
Example 4
Source Project: usergrid   Source File: ProviderParamsDao.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Saves provider params to elastic search and uses owning username as id.
 *
 * @param pp    Provider parameters to be saved
 * @return      Whether the operation was successful
 * @throws Exception
 */
public boolean save( final ProviderParams pp ) throws IOException {

    IndexResponse response = elasticSearchClient.getClient()
            .prepareIndex( DAO_INDEX_KEY, DAO_TYPE_KEY, pp.getUsername() )
            .setRefresh( true )
            .setSource(
                    jsonBuilder()
                            .startObject()
                            .field( "username", pp.getUsername() )
                            .field( "instanceType", pp.getInstanceType() )
                            .field( "accessKey", pp.getAccessKey() )
                            .field( "secretKey", pp.getSecretKey() )
                            .field( "imageId", pp.getImageId() )
                            .field( "keyName", pp.getKeyName() )
                            .field( "keys", pp.getKeys().toString() )
            )
            .execute()
            .actionGet();

    return response.isCreated();
}
 
Example 5
Source Project: usergrid   Source File: UserDao.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Stores a new user, username is used as ID, since it should be unique
 *
 * @param user  User to save
 * @return      whether the operation succeeded
 * @throws Exception
 */
public boolean save( User user ) throws IOException {

    IndexResponse response = elasticSearchClient.getClient()
            .prepareIndex( DAO_INDEX_KEY, DAO_TYPE_KEY, user.getUsername() )
            .setRefresh( true )
            .setSource(
                    jsonBuilder()
                            .startObject()
                            .field( "password", user.getPassword() )
                            .endObject()
            )
            .execute()
            .actionGet();

    return response.isCreated();
}
 
Example 6
Source Project: usergrid   Source File: NoteDao.java    License: Apache License 2.0 6 votes vote down vote up
public boolean save( Note note ) throws IOException {

        IndexResponse response = elasticSearchClient.getClient()
                .prepareIndex( DAO_INDEX_KEY, DAO_TYPE_KEY, note.getId() )
                .setRefresh( true )
                .setSource(
                        jsonBuilder()
                                .startObject()
                                .field( "commitId", note.getCommitId() )
                                .field( "runNumber", note.getRunNumber() )
                                .field( "text", note.getText() )
                                .endObject()
                )
                .execute()
                .actionGet();

        return response.isCreated();
    }
 
Example 7
private void onIndexAnomalyDetectorJobResponse(IndexResponse response, AnomalyDetectorFunction function) throws IOException {
    if (response == null || (response.getResult() != CREATED && response.getResult() != UPDATED)) {
        channel.sendResponse(new BytesRestResponse(response.status(), response.toXContent(channel.newErrorBuilder(), EMPTY_PARAMS)));
        return;
    }
    if (function != null) {
        function.execute();
    } else {
        XContentBuilder builder = channel
            .newBuilder()
            .startObject()
            .field(RestHandlerUtils._ID, response.getId())
            .field(RestHandlerUtils._VERSION, response.getVersion())
            .field(RestHandlerUtils._SEQ_NO, response.getSeqNo())
            .field(RestHandlerUtils._PRIMARY_TERM, response.getPrimaryTerm())
            .endObject();
        channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));
    }
}
 
Example 8
Source Project: jakduk-api   Source File: SearchService.java    License: MIT License 6 votes vote down vote up
public void indexDocumentGallery(EsGallery esGallery) {

		String id = esGallery.getId();

		try {
			IndexResponse response = client.prepareIndex()
					.setIndex(elasticsearchProperties.getIndexGallery())
					.setType(Constants.ES_TYPE_GALLERY)
					.setId(id)
					.setSource(ObjectMapperUtils.writeValueAsString(esGallery), XContentType.JSON)
					.get();

		} catch (IOException e) {
			throw new ServiceException(ServiceError.ELASTICSEARCH_INDEX_FAILED, e.getCause());
		}
	}
 
Example 9
Source Project: anomaly-detection   Source File: CheckpointDaoTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void putModelCheckpoint_getIndexRequest() {
    checkpointDao.putModelCheckpoint(modelId, model);

    ArgumentCaptor<IndexRequest> indexRequestCaptor = ArgumentCaptor.forClass(IndexRequest.class);
    verify(clientUtil)
        .timedRequest(
            indexRequestCaptor.capture(),
            anyObject(),
            Matchers.<BiConsumer<IndexRequest, ActionListener<IndexResponse>>>anyObject()
        );
    IndexRequest indexRequest = indexRequestCaptor.getValue();
    assertEquals(indexName, indexRequest.index());
    assertEquals(CheckpointDao.DOC_TYPE, indexRequest.type());
    assertEquals(modelId, indexRequest.id());
    Set<String> expectedSourceKeys = new HashSet<String>(Arrays.asList(CheckpointDao.FIELD_MODEL, CheckpointDao.TIMESTAMP));
    assertEquals(expectedSourceKeys, indexRequest.sourceAsMap().keySet());
    assertEquals(model, indexRequest.sourceAsMap().get(CheckpointDao.FIELD_MODEL));
    assertNotNull(indexRequest.sourceAsMap().get(CheckpointDao.TIMESTAMP));
}
 
Example 10
Source Project: Elasticsearch   Source File: BulkItemResponse.java    License: 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 11
Source Project: io   Source File: EsTypeImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * ドキュメントが登録されているかのチェックを行う.
 * @param id UUID
 * @param data Request body
 * @param ese ElasticSearchException
 * @return ES応答
 */
@SuppressWarnings("rawtypes")
protected IndexResponse checkDocumentCreated(String id, Map data, ElasticsearchException ese) {
    DcGetResponse getResponse = get(id);
    if (getResponse != null) {
        Object reqUpdated = data.get("u");
        Object getUpdated = getResponse.getSource().get("u");
        if (reqUpdated == null && getUpdated == null) {
            // uがnullになることはありえないが、静的チェックの指摘回避
            log.info("Request data is already registered. Then, return success response. But value is null");
            return new IndexResponse(indexName, getType(), id, 1, false);
        } else if ((reqUpdated != null && getUpdated != null) && reqUpdated.equals(getUpdated)) {
            log.info("Request data is already registered. Then, return success response.");
            return new IndexResponse(indexName, getType(), id, 1, false);
        }
    }
    throw new EsClientException("create failed", ese);
}
 
Example 12
Source Project: io   Source File: EsTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * ドキュメント登録チェックでドキュメントがすでに存在している場合に正常終了すること.
 * @throws ParseException ParseException
 */
@Test
public void ドキュメント登録チェックでドキュメントがすでに存在している場合に正常終了すること() throws ParseException {
    String id = "id00001";
    EsIndex index = esClient.idxAdmin("index_for_test");
    index.create();
    EsTypeImpl type = (EsTypeImpl) esClient.type(index.getName(), "TypeForTest", "TestRoutingId", 5, 500);
    assertNotNull(type);
    JSONObject data = (JSONObject) new JSONParser()
    .parse("{\"u\":1406596187938,\"t\":\"K0QK5DXWT5qKIPDU2eTdhA\",\"b\":\"IKv5hMRPRDGc68BnIcVx6g\","
            + "\"s\":{\"P003\":\"secondDynamicPropertyValue\",\"P002\":\"true\",\"P001\":\"false\","
            + "\"P011\":\"null\",\"P012\":\"123.0\",\"P007\":\"123\",\"P006\":\"false\",\"P005\":null,"
            + "\"P004\":\"dynamicPropertyValue\",\"P009\":\"123.123\",\"P008\":\"true\",\"__id\":\"userdata001:\","
            + "\"P010\":\"123.123\"},\"c\":\"Q1fp4zrWTm-gSSs7zVCJQg\",\"p\":1406596187938,"
            + "\"n\":\"vWy9OQj2ScykYize2d7Z5A\",\"l\":[],\"h\":{}}");
    type.create(id, data);
    IndexResponse response = type.checkDocumentCreated(id, data, null);
    assertNotNull(response);
    assertEquals(id, response.getId());
}
 
Example 13
Source Project: jframe   Source File: TestTransportClient.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testIndex() throws IOException {
    IndexResponse response = client.prepareIndex("twitter", "tweet", "1").setSource(XContentFactory.jsonBuilder().startObject()
            .field("user", "kimchy").field("postDate", new Date()).field("message", "trying out Elasticsearch").endObject()).get();
    // Index name
    String _index = response.getIndex();
    // Type name
    String _type = response.getType();
    // Document ID (generated or not)
    String _id = response.getId();
    // Version (if it's the first time you index this document, you will
    // get: 1)
    long _version = response.getVersion();
    // isCreated() is true if the document is a new one, false if it has
    // been updated
    boolean created = response.isCreated();
    System.out.println(response.toString());

}
 
Example 14
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 15
private void createUserID(final long userID) {
    final GetResponse getResponse = client
            .prepareGet(userIndex, userType, Long.toString(userID))
            .setRefresh(true).execute().actionGet();
    if (!getResponse.isExists()) {
        final Map<String, Object> source = new HashMap<>();
        source.put("system_id", Long.toString(userID));
        source.put(userIdField, userID);
        source.put(timestampField, new Date());
        final IndexResponse response = client
                .prepareIndex(userIndex, userType, Long.toString(userID))
                .setSource(source).setRefresh(true).execute().actionGet();
        if (!response.isCreated()) {
            throw new TasteException("Failed to create " + source);
        }
    }
}
 
Example 16
Source Project: tutorials   Source File: ElasticSearchManualTest.java    License: 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 17
@Override
public void callback(String documentId, JsonNode changes) {

    JsonNode allowed = copyOnlyAllowedFields(changes);

    if (allowed == null) {
        log.info("Document with id: '{}' was changed, but none of the fields are allowed to be sent to the ES",
                documentId);
        return;
    }

    IndexResponse response = client.prepareIndex(indexName, typeName, documentId)
            .setSource(allowed.toString(), XContentType.JSON)
            .get();

    log.info("Elasticsearch Index Response: '{}'", response);
}
 
Example 18
Source Project: arctic-sea   Source File: ElasticsearchDataHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public IndexResponse persist(Map<String, Object> dataMap) throws ElasticsearchGenerationException, IOException {
    if (!settings.isLoggingEnabled()) {
        return null;
    }
    if (adminHandler.getElasticsearchClient() == null) {
        throw new NullPointerException("Client is not initialized. Data will not be persisted.");
    }

    dataMap.put(ServiceEventDataMapping.TIMESTAMP_FIELD.getName(), DateTime.now(DateTimeZone.UTC));
    dataMap.put(ServiceEventDataMapping.UUID_FIELD.getName(), settings.getUuid());
    logger.debug("Persisting {}", dataMap);
    IndexResponse response = adminHandler.getElasticsearchClient().index(
            new IndexRequest(settings.getIndexId()).type(settings.getTypeId()).source(dataMap),
            RequestOptions.DEFAULT);
    return response;
}
 
Example 19
Source Project: arctic-sea   Source File: EmbeddedServerIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void connectEmbeddedMode() throws Exception {

    settings.setNodeConnectionMode(ElasticsearchSettingsKeys.CONNECTION_MODE_EMBEDDED_SERVER);
    adminHandler.init();

    Map<String, Object> data = new HashMap<>();
    data.put("test", "test-string");
    IndexResponse idx = dataHandler.persist(data);

    Thread.sleep(2000);

    String ret = dataHandler.getClient().get(new GetRequest(idx.getIndex(), idx.getId()), RequestOptions.DEFAULT)
            .getSourceAsString();
    Assertions.assertNotNull(ret);

    adminHandler.destroy();

    try {
        FileUtils.deleteDirectory(new File("./elasticsearch"));
    } catch (IOException e) {
        logger.info(e.getMessage(), e);
    }
}
 
Example 20
@Test
public void testIndexResponse() throws Exception {
    
    String body = "{\"_index\":\"%s\",\"_type\":\"index-pattern\",\"_id\":\"0\",\"_version\":1,\"result\":\"created\",\"_shards\":"
            + "{\"total\":2,\"successful\":1,\"failed\":0},\"created\":true}";
    
    XContentParser parser = XCONTENT.createParser(NamedXContentRegistry.EMPTY, String.format(body, KIBANA_INDEX));
    IndexResponse actionResponse = IndexResponse.fromXContent(parser);
    
    OpenShiftRestResponse osResponse = whenCreatingResponseResponse(actionResponse);
    thenResponseShouldBeModified(osResponse, body);
}
 
Example 21
Source Project: io   Source File: EsTypeImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
IndexResponse onParticularError(ElasticsearchException e) {
    if (e instanceof IndexMissingException || e.getCause() instanceof IndexMissingException) {
        throw new EsClientException.EsIndexMissingException(e);
    }
    if (e instanceof VersionConflictEngineException) {
        throw new EsClientException.EsVersionConflictException(e);
    }
    if (e instanceof MapperParsingException) {
        throw new EsClientException.EsSchemaMismatchException(e);
    }
    throw e;
}
 
Example 22
Source Project: ProjectStudy   Source File: HighLevelRestController.java    License: MIT License 5 votes vote down vote up
/**
 * 添加文档
 *
 * @param bookDto
 * @return com.example.common.ResponseBean
 * @throws
 * @author wliduo[[email protected]]
 * @date 2019/8/15 16:01
 */
@PostMapping("/book")
public ResponseBean add(@RequestBody BookDto bookDto) throws IOException {
    // IndexRequest
    IndexRequest indexRequest = new IndexRequest(Constant.INDEX);
    Long id = System.currentTimeMillis();
    bookDto.setId(id);
    String source = JSON.toJSONString(bookDto);
    indexRequest.id(id.toString()).source(source, XContentType.JSON);
    // 操作ES
    IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
    return new ResponseBean(HttpStatus.OK.value(), "添加成功", indexResponse);
}
 
Example 23
Source Project: glowroot   Source File: ElasticsearchAsyncIT.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void executeApp() throws Exception {
    client = Util.client(new InetSocketAddress("127.0.0.1", 9300));
    IndexResponse response = client.prepareIndex("testindex", "testtype")
            .setSource("abc", 11, "xyz", "some text")
            .get();
    documentId = response.getId();
    transactionMarker();
    client.close();
}
 
Example 24
Source Project: code   Source File: Save.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * HttpHost : url地址封装
 * RestClientBuilder: rest客户端构建器
 * RestHighLevelClient: rest高级客户端
 * IndexRequest: 新增或修改请求
 * IndexResponse:新增或修改的响应结果
 */
public static void main(String[] args) throws IOException {
    //1.连接rest接口
    HttpHost http = new HttpHost("127.0.0.1", 9200, "http");
    // rest构建器
    RestClientBuilder builder = RestClient.builder(http);
    // 高级客户端对象
    RestHighLevelClient restHighLevelClient = new RestHighLevelClient(builder);
    //2.封装请求对象
    IndexRequest indexRequest = new IndexRequest("sku", "doc", "3");
    Map<String, Object> skuMap = new HashMap<String, Object>();
    skuMap.put("name", "华为p30pro");
    skuMap.put("brandName", "华为");
    skuMap.put("categoryName", "手机");
    skuMap.put("price", 1010221);
    skuMap.put("createTime", "2019-05-01");
    skuMap.put("saleNum", 101021);
    skuMap.put("commentNum", 10102321);
    Map<String, Object> spec = new HashMap<String, Object>();
    spec.put("网络制式", "移动4G");
    spec.put("屏幕尺寸", "5");
    skuMap.put("spec", spec);
    indexRequest.source(skuMap);
    //3.获取响应结果
    IndexResponse response = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
    int status = response.status().getStatus();
    System.out.println("响应状态:" + status);
    restHighLevelClient.close();
}
 
Example 25
Source Project: dk-fitting   Source File: ESUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static IndexResponse insert(String hostIps, int port, String clusterName, String index, String type, String id, XContentBuilder b) throws Exception{
    client = getClient(hostIps,port,clusterName);
    //插入数据
    IndexRequestBuilder indexBuilder = client.prepareIndex(index, type, id).setSource(b);
    IndexResponse response = indexBuilder.execute().actionGet();
    return response;
}
 
Example 26
Source Project: elasticsearch-auth   Source File: AuthService.java    License: Apache License 2.0 5 votes vote down vote up
public void createToken(final Set<String> roleSet,
        final ActionListener<String> listener) {
    if (roleSet == null || roleSet.isEmpty()) {
        listener.onFailure(new AuthException(RestStatus.BAD_REQUEST,
                "Role is empty."));
        return;
    }

    final String token = generateToken();

    final Map<String, Object> sourceMap = new HashMap<String, Object>();
    sourceMap.put("roles", roleSet);
    sourceMap.put("lastModified", new Date());
    client.prepareIndex(authTokenIndex, tokenType, token)
            .setSource(sourceMap).setRefresh(true)
            .execute(new ActionListener<IndexResponse>() {
                @Override
                public void onResponse(final IndexResponse response) {
                    listener.onResponse(token);
                }

                @Override
                public void onFailure(final Throwable e) {
                    listener.onFailure(e);
                }
            });
}
 
Example 27
Source Project: spider   Source File: SpiderInfoDAO.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public String index(SpiderInfo spiderInfo) {
    IndexResponse indexResponse;
    if (getByDomain(spiderInfo.getDomain(), 10, 1).size() > 0) {
        List<SpiderInfo> mayDuplicate = Lists.newLinkedList();
        List<SpiderInfo> temp;
        int i = 1;
        do {
            temp = getByDomain(spiderInfo.getDomain(), 100, i++);
            mayDuplicate.addAll(temp);
        } while (temp.size() > 0);
        if (mayDuplicate.indexOf(spiderInfo) != -1 && (spiderInfo = mayDuplicate.get(mayDuplicate.indexOf(spiderInfo))) != null) {
            LOG.warn("已经含有此模板,不再存储");
            return spiderInfo.getId();
        }
    }
    try {
        indexResponse = client.prepareIndex(INDEX_NAME, TYPE_NAME)
                .setSource(gson.toJson(spiderInfo))
                .get();
        LOG.debug("索引爬虫模板成功");
        return indexResponse.getId();
    } catch (Exception e) {
        LOG.error("索引 Webpage 出错," + e.getLocalizedMessage());
    }
    return null;
}
 
Example 28
Source Project: io   Source File: EsRetryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ActionFuture<IndexResponse> asyncIndex(String index,
        String type,
        String id,
        String routingId,
        Map<String, Object> data,
        OpType opType,
        long version) {
    throwException();
    return super.asyncIndex(index, type, id, routingId, data, opType, version);
}
 
Example 29
Source Project: summerframework   Source File: ElasticsearchTemplate.java    License: Apache License 2.0 5 votes vote down vote up
public boolean addData(ESBasicInfo esBasicInfo, Object object) throws IOException {
    IndexResponse result =
        esClient.prepareIndex(esBasicInfo.getIndex(), esBasicInfo.getType(), esBasicInfo.getIds()[0])
            .setSource(mapper.writeValueAsString(object), XContentType.JSON).get();

    return result.status().getStatus() == 201 || result.status().getStatus() == 200;
}
 
Example 30
Source Project: summerframework   Source File: ElasticsearchTemplate.java    License: Apache License 2.0 5 votes vote down vote up
public boolean addData(ESBasicInfo esBasicInfo, Object object) throws IOException {
    IndexResponse result =
        esClient.prepareIndex(esBasicInfo.getIndex(), esBasicInfo.getType(), esBasicInfo.getIds()[0])
            .setSource(mapper.writeValueAsString(object), XContentType.JSON).get();

    return result.status().getStatus() == 201 || result.status().getStatus() == 200;
}