当前位置: 首页>>代码示例>>Java>>正文


Java IndexResponse类代码示例

本文整理汇总了Java中org.elasticsearch.action.index.IndexResponse的典型用法代码示例。如果您正苦于以下问题:Java IndexResponse类的具体用法?Java IndexResponse怎么用?Java IndexResponse使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


IndexResponse类属于org.elasticsearch.action.index包,在下文中一共展示了IndexResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: indexJSONTableDocuments

import org.elasticsearch.action.index.IndexResponse; //导入依赖的package包/类
private void indexJSONTableDocuments(TransportClient client, String indexName, String typeName, String tablePath, String... fields) {

        loginTestUser(TEST_USER_NAME, TEST_USER_GROUP);

        // Create an OJAI connection to MapR cluster
        Connection connection = DriverManager.getConnection(CONNECTION_URL);

        // Get an instance of OJAI DocumentStore
        final DocumentStore store = connection.getStore(tablePath);

        DocumentStream documentStream = store.find(fields);
        for (Document document : documentStream) {

            IndexResponse response = client.prepareIndex(indexName, typeName, document.getId().getString())
                    .setSource(document.asJsonString(), XContentType.JSON)
                    .get();

            log.info("Elasticsearch Index Response: '{}'", response);
        }

        // Close this instance of OJAI DocumentStore
        store.close();

        // Close the OJAI connection and release any resources held by the connection
        connection.close();
    }
 
开发者ID:mapr-demos,项目名称:mapr-music,代码行数:27,代码来源:MaprMusicElasticSearchService.java

示例2: exercisePipeline

import org.elasticsearch.action.index.IndexResponse; //导入依赖的package包/类
private SearchResponse exercisePipeline(String inputText, String pipelineName) throws IOException {

        //Add the ingest pipeline
        WritePipelineResponse pipelineResponse = client().admin().cluster().preparePutPipeline(pipelineName, getProcessorConfig(pipelineName)).get();
        assertTrue("Failed to add ingest pipeline", pipelineResponse.isAcknowledged());

        //Add a document that uses the ingest pipeline
        IndexResponse indexResponse = client().prepareIndex("test", "test").setPipeline(pipelineName).setSource(XContentFactory.jsonBuilder().startObject().field("text", inputText).endObject()).get();
        assertTrue("Failed to index document correctly", indexResponse.status().equals(RestStatus.CREATED));
        //Force index refresh
        refresh("test");

        //Find the document
        SearchResponse response = client().prepareSearch("test").setQuery(QueryBuilders.matchAllQuery()).get();
        ElasticsearchAssertions.assertNoFailures(response);

        return response;
    }
 
开发者ID:rosette-api,项目名称:rosette-elasticsearch-plugin,代码行数:19,代码来源:RosetteTextAnalysisPluginIT.java

示例3: execute

import org.elasticsearch.action.index.IndexResponse; //导入依赖的package包/类
public void execute(Tuple input, BasicOutputCollector collector) {
	Map<String, Object> value = null;

	// Check type and based on it processing the value
	if (type.equalsIgnoreCase("tdr")) {
		VehicleSensor vehicleSensor = (VehicleSensor) input.getValueByField("parsedstream");
		// Converting POJO object into Map
		value = convertVehicleSensortoMap(vehicleSensor);
	} else if (type.equalsIgnoreCase("alert")) {
		AlertEvent alertEvent = (AlertEvent) input.getValueByField("generatedAlertInfo");
		//Converting POJO object into Map
		value = convertVehicleAlerttoMap(alertEvent);
	}

	// Inserting into Elasticsearch
	IndexResponse response = client.prepareIndex(index, type).setSource(value).get();
	System.out.println(response.status());
}
 
开发者ID:PacktPublishing,项目名称:Practical-Real-time-Processing-and-Analytics,代码行数:19,代码来源:ElasticSearchBolt.java

示例4: callback

import org.elasticsearch.action.index.IndexResponse; //导入依赖的package包/类
@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);
}
 
开发者ID:mapr-demos,项目名称:mapr-music,代码行数:18,代码来源:MaprElasticSearchServiceBuilder.java

示例5: CreateDocument

import org.elasticsearch.action.index.IndexResponse; //导入依赖的package包/类
/**
 * This method Create the Index and insert the document(s)
 */
@Override
public void CreateDocument() {

    try {
        client = ESclient.getInstant();
        IndexResponse response = client.prepareIndex("school", "tenth", "1")
                .setSource(jsonBuilder()
                        .startObject()
                        .field("name", "Sundar")
                        .endObject()
                ).get();
        if (response != null) {
            String _index = response.getIndex();
            String _type = response.getType();
            String _id = response.getId();
            long _version = response.getVersion();
            RestStatus status = response.status();
            log.info("Index has been created successfully with Index: " + _index + " / Type: " + _type + "ID: " + _id);
        }
    } catch (IOException ex) {
        log.error("Exception occurred while Insert Index : " + ex, ex);
    }
}
 
开发者ID:sundarcse1216,项目名称:es-crud,代码行数:27,代码来源:ElasticSearchCrudImpl.java

示例6: testExternalVersioningInitialDelete

import org.elasticsearch.action.index.IndexResponse; //导入依赖的package包/类
public void testExternalVersioningInitialDelete() throws Exception {
    createIndex("test");
    ensureGreen();

    // Note - external version doesn't throw version conflicts on deletes of non existent records. This is different from internal versioning

    DeleteResponse deleteResponse = client().prepareDelete("test", "type", "1").setVersion(17).setVersionType(VersionType.EXTERNAL).execute().actionGet();
    assertEquals(DocWriteResponse.Result.NOT_FOUND, deleteResponse.getResult());

    // this should conflict with the delete command transaction which told us that the object was deleted at version 17.
    assertThrows(
            client().prepareIndex("test", "type", "1").setSource("field1", "value1_1").setVersion(13).setVersionType(VersionType.EXTERNAL).execute(),
            VersionConflictEngineException.class
    );

    IndexResponse indexResponse = client().prepareIndex("test", "type", "1").setSource("field1", "value1_1").setVersion(18).
            setVersionType(VersionType.EXTERNAL).execute().actionGet();
    assertThat(indexResponse.getVersion(), equalTo(18L));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:20,代码来源:SimpleVersioningIT.java

示例7: canIndexDocument

import org.elasticsearch.action.index.IndexResponse; //导入依赖的package包/类
private void canIndexDocument(String index) {
    try {
        IndexRequestBuilder builder = client().prepareIndex(index, "zzz");
        builder.setSource("foo", "bar");
        IndexResponse r = builder.execute().actionGet();
        assertThat(r, notNullValue());
    } catch (ClusterBlockException e) {
        fail();
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:11,代码来源:SimpleBlocksIT.java

示例8: testInheritMaxValidAutoIDTimestampOnRecovery

import org.elasticsearch.action.index.IndexResponse; //导入依赖的package包/类
public void testInheritMaxValidAutoIDTimestampOnRecovery() throws Exception {
    try (ReplicationGroup shards = createGroup(0)) {
        shards.startAll();
        final IndexRequest indexRequest = new IndexRequest(index.getName(), "type").source("{}", XContentType.JSON);
        indexRequest.onRetry(); // force an update of the timestamp
        final IndexResponse response = shards.index(indexRequest);
        assertEquals(DocWriteResponse.Result.CREATED, response.getResult());
        if (randomBoolean()) { // lets check if that also happens if no translog record is replicated
            shards.flush();
        }
        IndexShard replica = shards.addReplica();
        shards.recoverReplica(replica);

        SegmentsStats segmentsStats = replica.segmentStats(false);
        SegmentsStats primarySegmentStats = shards.getPrimary().segmentStats(false);
        assertNotEquals(IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, primarySegmentStats.getMaxUnsafeAutoIdTimestamp());
        assertEquals(primarySegmentStats.getMaxUnsafeAutoIdTimestamp(), segmentsStats.getMaxUnsafeAutoIdTimestamp());
        assertNotEquals(Long.MAX_VALUE, segmentsStats.getMaxUnsafeAutoIdTimestamp());
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:21,代码来源:IndexLevelReplicationTests.java

示例9: testThreadedListeners

import org.elasticsearch.action.index.IndexResponse; //导入依赖的package包/类
public void testThreadedListeners() throws Throwable {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> failure = new AtomicReference<>();
    final AtomicReference<String> threadName = new AtomicReference<>();
    Client client = client();

    IndexRequest request = new IndexRequest("test", "type", "1");
    if (randomBoolean()) {
        // set the source, without it, we will have a verification failure
        request.source(Requests.INDEX_CONTENT_TYPE, "field1", "value1");
    }

    client.index(request, new ActionListener<IndexResponse>() {
        @Override
        public void onResponse(IndexResponse indexResponse) {
            threadName.set(Thread.currentThread().getName());
            latch.countDown();
        }

        @Override
        public void onFailure(Exception e) {
            threadName.set(Thread.currentThread().getName());
            failure.set(e);
            latch.countDown();
        }
    });

    latch.await();

    boolean shouldBeThreaded = TransportClient.CLIENT_TYPE.equals(Client.CLIENT_TYPE_SETTING_S.get(client.settings()));
    if (shouldBeThreaded) {
        assertTrue(threadName.get().contains("listener"));
    } else {
        assertFalse(threadName.get().contains("listener"));
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:37,代码来源:ListenerActionIT.java

示例10: indexFact

import org.elasticsearch.action.index.IndexResponse; //导入依赖的package包/类
/**
 * Index a Fact into ElasticSearch.
 *
 * @param fact Fact to index
 * @return Indexed Fact
 */
public FactDocument indexFact(FactDocument fact) {
  if (fact == null || fact.getId() == null) return null;
  IndexResponse response;

  try {
    IndexRequest request = new IndexRequest(INDEX_NAME, TYPE_NAME, fact.getId().toString())
            .source(FACT_DOCUMENT_WRITER.writeValueAsBytes(encodeValues(fact)), XContentType.JSON);
    response = clientFactory.getHighLevelClient().index(request);
  } catch (IOException ex) {
    throw logAndExit(ex, String.format("Could not perform request to index Fact with id = %s.", fact.getId()));
  }

  if (response.status() != RestStatus.OK && response.status() != RestStatus.CREATED) {
    LOGGER.warning("Could not index Fact with id = %s.", fact.getId());
  } else if (response.getResult() == DocWriteResponse.Result.CREATED) {
    LOGGER.info("Successfully indexed Fact with id = %s.", fact.getId());
  } else if (response.getResult() == DocWriteResponse.Result.UPDATED) {
    LOGGER.info("Successfully re-indexed existing Fact with id = %s.", fact.getId());
  }

  return fact;
}
 
开发者ID:mnemonic-no,项目名称:act-platform,代码行数:29,代码来源:FactSearchManager.java

示例11: insert

import org.elasticsearch.action.index.IndexResponse; //导入依赖的package包/类
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;
}
 
开发者ID:dev-share,项目名称:css-elasticsearch,代码行数:17,代码来源:ElasticsearchTransportFactory.java

示例12: CreateIndex

import org.elasticsearch.action.index.IndexResponse; //导入依赖的package包/类
private static void CreateIndex(Client client){
    String json = "{" +
            "\"user\":\"daiyutage\"," +
            "\"postDate\":\"2013-01-30\"," +
            "\"message\":\"trying out Elasticsearch\"" +
            "}";

    IndexResponse response = client.prepareIndex("twitter", "tweet","2")
            .setSource(json)
            .get();
    // Index name
    String _index = response.getIndex();
    System.out.println("index:"+_index);
    // Type name  
    String _type = response.getType();
    System.out.println("_type:"+_type);
    // 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();
    System.out.println("_version:"+_version);
    // isCreated() is true if the document is a new one, false if it has been updated  
    boolean created = response.isCreated();

}
 
开发者ID:hs-web,项目名称:hsweb-learning,代码行数:26,代码来源:ElasticSearch.java

示例13: index

import org.elasticsearch.action.index.IndexResponse; //导入依赖的package包/类
@Override
public void index(String appid, ParaObject po) {
	if (po == null || StringUtils.isBlank(appid)) {
		return;
	}
	try {
		IndexRequestBuilder irb = client().prepareIndex(getIndexName(appid), getType(), po.getId()).
				setSource(ElasticSearchUtils.getSourceFromParaObject(po));
		ActionListener<IndexResponse> responseHandler = ElasticSearchUtils.getIndexResponseHandler();
		if (isAsyncEnabled()) {
			irb.execute(responseHandler);
		} else {
			responseHandler.onResponse(irb.execute().actionGet());
		}
		logger.debug("Search.index() {}", po.getId());
	} catch (Exception e) {
		logger.warn(null, e);
	}
}
 
开发者ID:Erudika,项目名称:para-search-elasticsearch,代码行数:20,代码来源:ElasticSearch.java

示例14: writeTo

import org.elasticsearch.action.index.IndexResponse; //导入依赖的package包/类
@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);
    }
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:25,代码来源:BulkItemResponse.java

示例15: shardIndexOperation

import org.elasticsearch.action.index.IndexResponse; //导入依赖的package包/类
private WriteResult<IndexResponse> shardIndexOperation(BulkShardRequest request, IndexRequest indexRequest, MetaData metaData,
                                        IndexShard indexShard, boolean processed) throws Throwable {
    indexShard.checkDiskSpace(fsService);
    // validate, if routing is required, that we got routing
    MappingMetaData mappingMd = metaData.index(request.index()).mappingOrDefault(indexRequest.type());
    if (mappingMd != null && mappingMd.routing().required()) {
        if (indexRequest.routing() == null) {
            throw new RoutingMissingException(request.index(), indexRequest.type(), indexRequest.id());
        }
    }

    if (!processed) {
        indexRequest.process(metaData, mappingMd, allowIdGeneration, request.index());
    }

    return TransportIndexAction.executeIndexRequestOnPrimary(request, indexRequest, indexShard, mappingUpdatedAction);
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:18,代码来源:TransportShardBulkAction.java


注:本文中的org.elasticsearch.action.index.IndexResponse类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。