Java Code Examples for org.elasticsearch.action.get.GetResponse#getSourceAsString()

The following examples show how to use org.elasticsearch.action.get.GetResponse#getSourceAsString() . 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: Test.java    From dht-spider with MIT License 6 votes vote down vote up
public static void get(Map<String, Object> m) throws Exception{
    GetRequest getRequest = new GetRequest(
            "haha",
            "doc",
            "2");
    String[] includes = new String[]{"message","user","*Date"};
    String[] excludes = Strings.EMPTY_ARRAY;
    FetchSourceContext fetchSourceContext =
            new FetchSourceContext(true, includes, excludes);
    getRequest.fetchSourceContext(fetchSourceContext);

    GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
    String index = getResponse.getIndex();
    String type = getResponse.getType();
    String id = getResponse.getId();
    if (getResponse.isExists()) {
        long version = getResponse.getVersion();
        String sourceAsString = getResponse.getSourceAsString();
        Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
        System.out.println(sourceAsMap);
    } else {

    }
}
 
Example 2
Source File: TransportClient.java    From elasticsearch-jest-example with MIT License 6 votes vote down vote up
/**
 * 获取索引信息
 * @param index
 * @param type
 * @param id
 */
private static void getIndex(String index, String type, String id){
	Client client = createTransportClient();
	GetResponse response = client.prepareGet(index, type, id)
	        .execute()
	        .actionGet();
	boolean exists = response.isExists();
	System.out.println(exists);// 判断索引是否存在
	String sourceString = response.getSourceAsString();
	System.out.println(sourceString);// 获取索引,并且打印出索引内容
	System.out.println("****************index ***********************");
	// 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();
	System.out.println(_index+","+_type+","+_id+","+_version);
}
 
Example 3
Source File: BaseDemo.java    From Elasticsearch-Tutorial-zh-CN with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 获取多个对象(根据ID)
 *
 * @param transportClient
 * @throws IOException
 */
private static void queryByMultiGet(TransportClient transportClient) throws IOException {

	MultiGetResponse multiGetItemResponses = transportClient.prepareMultiGet()
			.add("product_index", "product", "1")
			.add("product_index", "product", "2")
			.add("product_index", "product", "3")
			.add("product_index", "product", "4")
			.add("product_index", "product", "5")
			.get();

	String resultJSON = null;
	for (MultiGetItemResponse multiGetItemResponse : multiGetItemResponses) {
		GetResponse getResponse = multiGetItemResponse.getResponse();
		if (getResponse.isExists()) {
			resultJSON = getResponse.getSourceAsString();
		}
	}
	logger.info("--------------------------------:" + resultJSON);
}
 
Example 4
Source File: ElasticsearchTemplate.java    From summerframework with Apache License 2.0 5 votes vote down vote up
public <T> T query(ESBasicInfo esBasicInfo, Class<T> clazz) throws IOException {
    GetRequestBuilder requestBuilder =
        esClient.prepareGet(esBasicInfo.getIndex(), esBasicInfo.getType(), esBasicInfo.getIds()[0]);
    GetResponse response = requestBuilder.execute().actionGet();

    return response.getSourceAsString() != null ? mapper.readValue(response.getSourceAsString(), clazz) : null;
}
 
Example 5
Source File: TestTransportClient.java    From jframe with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiGet() {
    MultiGetResponse multiGetItemResponses = client.prepareMultiGet().add("twitter", "tweet", "1").add("twitter", "tweet", "2", "3", "4")
            .add("another", "type", "foo").get();

    for (MultiGetItemResponse itemResponse : multiGetItemResponses) {
        GetResponse response = itemResponse.getResponse();
        if (response.isExists()) {
            String json = response.getSourceAsString();
            System.out.println(json);
        }
    }
}
 
Example 6
Source File: PersistentContainer.java    From sfs with Apache License 2.0 5 votes vote down vote up
public static PersistentContainer fromGetResponse(PersistentAccount persistentAccount, GetResponse getResponse) {
    JsonObject document = new JsonObject(getResponse.getSourceAsString());

    return
            new PersistentContainer(persistentAccount, getResponse.getId(), getResponse.getVersion())
                    .merge(document);

}
 
Example 7
Source File: PersistentServiceDef.java    From sfs with Apache License 2.0 5 votes vote down vote up
public static PersistentServiceDef fromGetResponse(GetResponse getResponse) {
    long persistentVersion = getResponse.getVersion();
    JsonObject document = new JsonObject(getResponse.getSourceAsString());

    return new PersistentServiceDef(getResponse.getId(), persistentVersion)
            .merge(document);
}
 
Example 8
Source File: ElasticSearchRepository.java    From elastic-crud with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public List<T> findAll(final List<String> ids) {
  if (ids.isEmpty()) {
    return ImmutableList.of();
  }

  final Builder<T> builder = ImmutableList.builder();

  final MultiGetResponse response = client
    .prepareMultiGet()
    .add(index, type, ids)
    .execute()
    .actionGet();

  for(final MultiGetItemResponse item : response.getResponses()) {
    final GetResponse get = item.getResponse();
    if(get.isSourceEmpty()) {
      continue;
    }

    final String json = get.getSourceAsString();
    final T entity = deserializer.apply(json);
    builder.add((T) entity.withId(get.getId()));
  }

  return builder.build();
}
 
Example 9
Source File: ElasticSearchRepository.java    From elastic-crud with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Optional<T> findOne(final String id) {
  final GetResponse response = client
    .prepareGet(index, type, id)
    .setFetchSource(true)
    .execute()
    .actionGet();
  final String json = response.getSourceAsString();
  return ofNullable(json)
    .map(deserializer)
    .map(e -> (T) e.withId(id));
}
 
Example 10
Source File: MultiGetDemo.java    From elasticsearch-full with Apache License 2.0 5 votes vote down vote up
@Test
public void name() throws Exception {
    MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
            .add("twitter", "tweet", "1")
            .add("twitter", "tweet", "2", "3", "4")
            .add("another", "type", "foo")
            .get();
    for (MultiGetItemResponse itemResponse : multiGetItemResponses) {
        GetResponse response = itemResponse.getResponse();
        if (response.isExists()) {
            String json = response.getSourceAsString();
        }
    }
}
 
Example 11
Source File: AbstractESTest.java    From elasticsearch-migration with Apache License 2.0 5 votes vote down vote up
@SneakyThrows
protected <T> T getFromIndex(String indexName, String type, String id, Class<T> clazz) {
    final ActionFuture<GetResponse> response = client.get(new GetRequest(indexName, type, id));
    client.admin().indices().prepareFlush(indexName).setWaitIfOngoing(true).setForce(true).execute().get();
    final GetResponse getFields = response.get();

    final String sourceAsString = getFields.getSourceAsString();

    return esObjectMapper.readValue(sourceAsString, clazz);
}
 
Example 12
Source File: AbstractESTest.java    From elasticsearch-migration with Apache License 2.0 5 votes vote down vote up
@SneakyThrows
protected String getFromIndex(String indexName, String type, String id) {
    final ActionFuture<GetResponse> response = client.get(new GetRequest(indexName, type, id).fetchSourceContext(FetchSourceContext.FETCH_SOURCE));
    client.admin().indices().prepareFlush(indexName).setWaitIfOngoing(true).setForce(true).execute().get();
    final GetResponse getFields = response.get();

    assertThat("Response should be done", response.isDone(), is(true));
    assertThat("Get " + id + " should exist (" + indexName + ", " + type + ")", getFields.isExists(), is(true));
    assertThat("Source field should not be empty", getFields.isSourceEmpty(), is(false));

    final String sourceAsString = getFields.getSourceAsString();

    assertThat("response source should not be null", sourceAsString, notNullValue());
    return sourceAsString;
}
 
Example 13
Source File: ElasticsearchTransportFactory.java    From database-transform-tool with Apache License 2.0 5 votes vote down vote up
public String select(String index,String type,String id){
	try {
		if(client==null){
			init();
		}
		GetResponse result = client.prepareGet(index, type, id).execute().actionGet();
		return result.getSourceAsString();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
}
 
Example 14
Source File: ElasticsearchHighRestFactory.java    From database-transform-tool with Apache License 2.0 5 votes vote down vote up
public String select(String index,String type,String id){
	try {
		if(xclient==null){
			init();
		}
		GetRequest request = new GetRequest(index, type, id);
		GetResponse result = xclient.get(request);
		return result.getSourceAsString();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
}
 
Example 15
Source File: ElasticsearchTemplate.java    From summerframework with Apache License 2.0 5 votes vote down vote up
public <T> T query(ESBasicInfo esBasicInfo, Class<T> clazz) throws IOException {
    GetRequestBuilder requestBuilder =
        esClient.prepareGet(esBasicInfo.getIndex(), esBasicInfo.getType(), esBasicInfo.getIds()[0]);
    GetResponse response = requestBuilder.execute().actionGet();

    return response.getSourceAsString() != null ? mapper.readValue(response.getSourceAsString(), clazz) : null;
}
 
Example 16
Source File: EsHighLevelRestTest2.java    From java-study with Apache License 2.0 4 votes vote down vote up
/**
	 * 多查询使用
	 * 
	 * @throws IOException
	 */
	private static void multiGet() throws IOException {

		MultiGetRequest request = new MultiGetRequest();
		request.add(new MultiGetRequest.Item("estest", "estest", "1"));
		request.add(new MultiGetRequest.Item("user", "userindex", "2"));
		// 禁用源检索,默认启用
//		request.add(new MultiGetRequest.Item("user", "userindex", "2").fetchSourceContext(FetchSourceContext.DO_NOT_FETCH_SOURCE));

		// 同步构建
		MultiGetResponse response = client.mget(request, RequestOptions.DEFAULT);

		// 异步构建
//		MultiGetResponse response2 = client.mgetAsync(request, RequestOptions.DEFAULT, listener);

		/*
		 * 返回的MultiGetResponse包含在' getResponses中的MultiGetItemResponse的列表,其顺序与请求它们的顺序相同。
		 * 如果成功,MultiGetItemResponse包含GetResponse或MultiGetResponse。如果失败了就失败。
		 * 成功看起来就像一个正常的GetResponse
		 */

		for (MultiGetItemResponse item : response.getResponses()) {
			assertNull(item.getFailure());
			GetResponse get = item.getResponse();
			String index = item.getIndex();
			String type = item.getType();
			String id = item.getId();
			// 如果请求存在
			if (get.isExists()) {
				long version = get.getVersion();
				String sourceAsString = get.getSourceAsString();
				Map<String, Object> sourceAsMap = get.getSourceAsMap();
				byte[] sourceAsBytes = get.getSourceAsBytes();
				System.out.println("查询的结果:" + sourceAsMap);
			} else {
				System.out.println("没有找到该文档!");
			}

		}

	}
 
Example 17
Source File: ElasticSearch.java    From hsweb-learning with Apache License 2.0 3 votes vote down vote up
public static void GetResponse(Client client){

        GetResponse reponse = client.prepareGet("twitter","tweet","2").get();

        String _source = reponse.getSourceAsString();

        System.out.println(_source);

    }
 
Example 18
Source File: PersistentObject.java    From sfs with Apache License 2.0 3 votes vote down vote up
public static PersistentObject fromGetResponse(PersistentContainer container, GetResponse getResponse) {

        String id = getResponse.getId();
        long persistentVersion = getResponse.getVersion();
        JsonObject document = new JsonObject(getResponse.getSourceAsString());

        return new PersistentObject(container, id, persistentVersion)
                .merge(document);

    }
 
Example 19
Source File: ElasticSearchDataReader.java    From pacbot with Apache License 2.0 3 votes vote down vote up
/**
 * 
 * @param index
 * @param type
 * @param id
 * @return
 * @throws IOException
 */
public String getDocumentById(String index,String type, String id,String parentId) throws IOException{
    GetRequest req = new GetRequest(index,type,id);
    req.routing(parentId);
    GetResponse response =    client.get(req);
    return response.getSourceAsString();
}