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

The following examples show how to use org.elasticsearch.action.get.GetResponse#getSourceAsMap() . 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: EsUtil.java    From java-study with Apache License 2.0 6 votes vote down vote up
/**
 * @return boolean
 * @Author pancm
 * @Description 根据id查询
 * @Date 2019/3/21
 * @Param []
 **/
public static Map<String, Object> queryById(String index, String type, String id) throws IOException {
    if (index == null || type == null) {
        return null;
    }
    Map<String, Object> map = new HashMap<>();
    try {
        GetRequest request = new GetRequest();
        request.index(index);
        request.type(type);
        request.id(id);
        GetResponse getResponse = client.get(request, RequestOptions.DEFAULT);
        // 如果存在该数据则返回对应的结果
        if (getResponse.isExists()) {
            map = getResponse.getSourceAsMap();
        }
    } finally {
        if (isAutoClose) {
            close();
        }
    }
    return map;
}
 
Example 3
Source File: ElasticsearchAdminHandlerIT.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void addnewUuidOnConnect() throws IOException {
    adminHandler.createSchema();
    clientSettings.setUuid("lofasz janos");

    adminHandler.createSchema();

    GetResponse resp = getEmbeddedClient()
            .get(new GetRequest(clientSettings.getIndexId(), MetadataDataMapping.METADATA_TYPE_NAME,
                    MetadataDataMapping.METADATA_ROW_ID), RequestOptions.DEFAULT);

    Map<String, Object> map = resp.getSourceAsMap();
    Assertions.assertNotNull(map.get(MetadataDataMapping.METADATA_CREATION_TIME_FIELD.getName()));
    Assertions.assertNotNull(map.get(MetadataDataMapping.METADATA_UUIDS_FIELD.getName()));
    Assertions.assertNotNull(map.get(MetadataDataMapping.METADATA_UPDATE_TIME_FIELD.getName()));

    List<String> object = (List<String>) map.get(MetadataDataMapping.METADATA_UUIDS_FIELD.getName());
    Assertions.assertEquals(2, object.size());
    MatcherAssert.assertThat(object, CoreMatchers.hasItem("lofasz janos"));
}
 
Example 4
Source File: ElasticSearchDAOV5.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Override
public String get(String workflowInstanceId, String fieldToGet) {
    GetRequest request = new GetRequest(indexName, WORKFLOW_DOC_TYPE, workflowInstanceId)
        .fetchSourceContext(
            new FetchSourceContext(true, new String[]{fieldToGet}, Strings.EMPTY_ARRAY));
    GetResponse response = elasticSearchClient.get(request).actionGet();

    if (response.isExists()) {
        Map<String, Object> sourceAsMap = response.getSourceAsMap();
        if (sourceAsMap.containsKey(fieldToGet)) {
            return sourceAsMap.get(fieldToGet).toString();
        }
    }

    logger.info("Unable to find Workflow: {} in ElasticSearch index: {}.", workflowInstanceId, indexName);
    return null;
}
 
Example 5
Source File: ElasticSearchRestDAOV5.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Override
public String get(String workflowInstanceId, String fieldToGet) {

    GetRequest request = new GetRequest(indexName, WORKFLOW_DOC_TYPE, workflowInstanceId);

    GetResponse response;
    try {
        response = elasticSearchClient.get(request);
    } catch (IOException e) {
        logger.error("Unable to get Workflow: {} from ElasticSearch index: {}", workflowInstanceId, indexName, e);
        return null;
    }

    if (response.isExists()){
        Map<String, Object> sourceAsMap = response.getSourceAsMap();
        if (sourceAsMap.containsKey(fieldToGet)){
            return sourceAsMap.get(fieldToGet).toString();
        }
    }

    logger.debug("Unable to find Workflow: {} in ElasticSearch index: {}.", workflowInstanceId, indexName);
    return null;
}
 
Example 6
Source File: ElasticSearchRestDAOV6.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Override
public String get(String workflowInstanceId, String fieldToGet) {

    String docType = StringUtils.isBlank(docTypeOverride) ? WORKFLOW_DOC_TYPE : docTypeOverride;
    GetRequest request = new GetRequest(workflowIndexName, docType, workflowInstanceId);

    GetResponse response;
    try {
        response = elasticSearchClient.get(request);
    } catch (IOException e) {
        logger
            .error("Unable to get Workflow: {} from ElasticSearch index: {}", workflowInstanceId, workflowIndexName,
                e);
        return null;
    }

    if (response.isExists()) {
        Map<String, Object> sourceAsMap = response.getSourceAsMap();
        if (sourceAsMap.get(fieldToGet) != null) {
            return sourceAsMap.get(fieldToGet).toString();
        }
    }

    logger.debug("Unable to find Workflow: {} in ElasticSearch index: {}.", workflowInstanceId, workflowIndexName);
    return null;
}
 
Example 7
Source File: ElasticSearchDAOV6.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Override
public String get(String workflowInstanceId, String fieldToGet) {
    String docType = StringUtils.isBlank(docTypeOverride) ? WORKFLOW_DOC_TYPE : docTypeOverride;
    GetRequest request = new GetRequest(workflowIndexName, docType, workflowInstanceId)
            .fetchSourceContext(new FetchSourceContext(true, new String[]{fieldToGet}, Strings.EMPTY_ARRAY));
    GetResponse response = elasticSearchClient.get(request).actionGet();

    if (response.isExists()) {
        Map<String, Object> sourceAsMap = response.getSourceAsMap();
        if (sourceAsMap.get(fieldToGet) != null) {
            return sourceAsMap.get(fieldToGet).toString();
        }
    }

    LOGGER.debug("Unable to find Workflow: {} in ElasticSearch index: {}.", workflowInstanceId, workflowIndexName);
    return null;
}
 
Example 8
Source File: MinHashPluginTest.java    From elasticsearch-minhash with Apache License 2.0 6 votes vote down vote up
private void test_get(final Client client, final String index,
        final String type, final String id, final byte[] hash1,
        final byte[] hash2, final byte[] hash3) {
    final GetResponse response = client.prepareGet(index, type, id)
            .setStoredFields(new String[] { "_source", "minhash_value1", "minhash_value2", "minhash_value3" }).execute()
            .actionGet();
    assertTrue(response.isExists());
    final Map<String, Object> source = response.getSourceAsMap();
    assertEquals("test " + Integer.parseInt(id) % 100, source.get("msg"));

    final DocumentField field1 = response.getField("minhash_value1");
    final BytesArray value1 = (BytesArray) field1.getValue();
    assertEquals(hash1.length, value1.length());
    Assert.assertArrayEquals(hash1, value1.array());

    final DocumentField field2 = response.getField("minhash_value2");
    final BytesArray value2 = (BytesArray) field2.getValue();
    assertEquals(hash2.length, value2.length());
    Assert.assertArrayEquals(hash2, value2.array());

    final DocumentField field3 = response.getField("minhash_value3");
    final BytesArray value3 = (BytesArray) field3.getValue();
    assertEquals(hash3.length, value3.length());
    Assert.assertArrayEquals(hash3, value3.array());
}
 
Example 9
Source File: ElasticsearchClient.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected static Map<String, Object> getMap(GetResponse response) {
    Map<String, Object> map = null;
    if (response.isExists() && (map = response.getSourceAsMap()) != null) {
        if (!map.containsKey("id")) map.put("id", response.getId());
        if (!map.containsKey("type")) map.put("type", response.getType());
    }
    return map;
}
 
Example 10
Source File: ElasticSearchUtilImpl.java    From metacat with Apache License 2.0 5 votes vote down vote up
private ElasticSearchDoc parse(final GetResponse response) {
    ElasticSearchDoc result = null;
    if (response.isExists()) {
        final Map<String, Object> responseMap = response.getSourceAsMap();
        final String user = (String) responseMap.get(ElasticSearchDoc.Field.USER);
        final boolean deleted = (boolean) responseMap.get(ElasticSearchDoc.Field.DELETED);
        final long timestamp = (long) responseMap.get(ElasticSearchDoc.Field.TIMESTAMP);
        @SuppressWarnings("unchecked") final Object dto = metacatJson.parseJsonValue(
            response.getSourceAsBytes(),
            getClass(response.getType())
        );
        result = new ElasticSearchDoc(response.getId(), dto, user, deleted, timestamp);
    }
    return result;
}
 
Example 11
Source File: ElasticsearchLockProviderTest.java    From ShedLock with Apache License 2.0 5 votes vote down vote up
@Override
protected void assertUnlocked(String lockName) {
    GetRequest gr = new GetRequest(SCHEDLOCK_DEFAULT_INDEX, SCHEDLOCK_DEFAULT_TYPE, lockName);
    try {
        GetResponse res = highLevelClient.get(gr, RequestOptions.DEFAULT);
        Map<String, Object> m = res.getSourceAsMap();
        assertThat(new Date((Long) m.get(LOCK_UNTIL))).isBeforeOrEqualsTo(now());
        assertThat(new Date((Long) m.get(LOCKED_AT))).isBeforeOrEqualsTo(now());
        assertThat((String) m.get(LOCKED_BY)).isNotBlank();
        assertThat((String) m.get(NAME)).isEqualTo(lockName);
    } catch (IOException e) {
        fail("Call to embedded ES failed.");
    }
}
 
Example 12
Source File: ElasticsearchLockProviderTest.java    From ShedLock with Apache License 2.0 5 votes vote down vote up
@Override
protected void assertLocked(String lockName) {
    GetRequest gr = new GetRequest(SCHEDLOCK_DEFAULT_INDEX, SCHEDLOCK_DEFAULT_TYPE, lockName);
    try {
        GetResponse res = highLevelClient.get(gr, RequestOptions.DEFAULT);
        Map<String, Object> m = res.getSourceAsMap();
        assertThat(new Date((Long) m.get(LOCK_UNTIL))).isAfter(now());
        assertThat(new Date((Long) m.get(LOCKED_AT))).isBeforeOrEqualsTo(now());
        assertThat((String) m.get(LOCKED_BY)).isNotBlank();
        assertThat((String) m.get(NAME)).isEqualTo(lockName);
    } catch (IOException e) {
        fail("Call to embedded ES failed.");
    }
}
 
Example 13
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 14
Source File: ElasticSearchRestHighImpl.java    From sunbird-lms-service with MIT License 4 votes vote down vote up
/**
 * This method will provide data form ES based on incoming identifier. we can get data by passing
 * index and identifier values , or all the three
 *
 * @param type String
 * @param identifier String
 * @return Map<String,Object> or empty map
 */
@Override
public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) {
  long startTime = System.currentTimeMillis();
  Promise<Map<String, Object>> promise = Futures.promise();
  if (StringUtils.isNotEmpty(identifier) && StringUtils.isNotEmpty(index)) {

    ProjectLogger.log(
        "ElasticSearchRestHighImpl:getDataByIdentifier: method started at =="
            + startTime
            + " for Index "
            + index,
        LoggerEnum.PERF_LOG.name());

    GetRequest getRequest = new GetRequest(index, _DOC, identifier);

    ActionListener<GetResponse> listener =
        new ActionListener<GetResponse>() {
          @Override
          public void onResponse(GetResponse getResponse) {
            if (getResponse.isExists()) {
              Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
              if (MapUtils.isNotEmpty(sourceAsMap)) {
                promise.success(sourceAsMap);
                ProjectLogger.log(
                    "ElasticSearchRestHighImpl:getDataByIdentifier: method end =="
                        + " for Index "
                        + index
                        + " ,Total time elapsed = "
                        + calculateEndTime(startTime),
                    LoggerEnum.PERF_LOG.name());
              } else {
                promise.success(new HashMap<>());
              }
            } else {
              promise.success(new HashMap<>());
            }
          }

          @Override
          public void onFailure(Exception e) {
            ProjectLogger.log(
                "ElasticSearchRestHighImpl:getDataByIdentifier: method Failed with error == " + e,
                LoggerEnum.INFO.name());
            promise.failure(e);
          }
        };

    ConnectionManager.getRestClient().getAsync(getRequest, listener);
  } else {
    ProjectLogger.log(
        "ElasticSearchRestHighImpl:getDataByIdentifier:  "
            + "provided index or identifier is null, index = "
            + index
            + ","
            + " identifier = "
            + identifier,
        LoggerEnum.INFO.name());
    promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData));
  }

  return promise.future();
}