Java Code Examples for org.elasticsearch.action.get.GetResponse

The following examples show how to use org.elasticsearch.action.get.GetResponse. 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
Source Project: dht-spider   Source File: Test.java    License: 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 Project: elasticsearch-river-web   Source File: ScriptService.java    License: Apache License 2.0 6 votes vote down vote up
private String getScriptContent(final String lang, final String script, final ScriptType scriptType) {
    switch (scriptType) {
    case INLINE:
        return script;
    case FILE:
        if (Files.exists(Paths.get(script))) {
            return FileUtil.readText(new File(script));
        } else {
            return FileUtil.readText(script);
        }
    case INDEXED:
        final GetResponse response = esClient.prepareGet(SCRIPT_INDEX, lang, script).execute().actionGet();
        if (!response.isExists()) {
            throw new ScriptExecutionException("/" + SCRIPT_INDEX + "/" + lang + "/" + script + " does not exist.");
        }
        final Map<String, Object> source = response.getSource();
        if (source != null) {
            return (String) source.get("script");
        }
        break;
    default:
        break;
    }
    return null;
}
 
Example 3
private ActionListener<GetResponse> onGetDetectorResponse(
    MultiResponsesDelegateActionListener<DetectorProfile> listener,
    String detectorId,
    Set<ProfileName> profiles
) {
    return ActionListener.wrap(getResponse -> {
        if (getResponse != null && getResponse.isExists()) {
            DetectorProfile profile = new DetectorProfile();
            if (profiles.contains(ProfileName.STATE)) {
                profile.setState(DetectorState.DISABLED);
            }
            listener.respondImmediately(profile);
        } else {
            listener.failImmediately(FAIL_TO_FIND_DETECTOR_MSG + detectorId);
        }
    }, exception -> { listener.failImmediately(FAIL_TO_FIND_DETECTOR_MSG + detectorId, exception); });
}
 
Example 4
Source Project: hawkular-apm   Source File: TraceServiceElasticsearch.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Trace getFragment(String tenantId, String id) {
    Trace ret = null;

    GetResponse response = client.getClient().prepareGet(
            client.getIndex(tenantId), TRACE_TYPE, id).setRouting(id)
            .execute()
            .actionGet();
    if (!response.isSourceEmpty()) {
        try {
            ret = mapper.readValue(response.getSourceAsString(), Trace.class);
        } catch (Exception e) {
            msgLog.errorFailedToParse(e);
        }
    }

    if (msgLog.isTraceEnabled()) {
        msgLog.tracef("Get fragment with id[%s] is: %s", id, ret);
    }

    return ret;
}
 
Example 5
private int getCounterValue(String host_user){

        try{
        	GetResponse response = client.prepareGet(index, type, host_user)
        	        .execute()
        	        .actionGet();
        	
        	Map<String, Object> test = response.getSource();
        	
        	return (int)test.get("counter");
        }
        catch (Exception e){
        	System.out.println("Error in get elasticSearch get: maybe index is still not created");
        	return 0;
        }
    }
 
Example 6
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 7
Source Project: anomaly-detection   Source File: ADStateManager.java    License: Apache License 2.0 6 votes vote down vote up
private ActionListener<GetResponse> onGetResponse(String adID, ActionListener<Optional<AnomalyDetector>> listener) {
    return ActionListener.wrap(response -> {
        if (response == null || !response.isExists()) {
            listener.onResponse(Optional.empty());
            return;
        }

        String xc = response.getSourceAsString();
        LOG.info("Fetched anomaly detector: {}", xc);

        try (
            XContentParser parser = XContentType.JSON.xContent().createParser(xContentRegistry, LoggingDeprecationHandler.INSTANCE, xc)
        ) {
            ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation);
            AnomalyDetector detector = AnomalyDetector.parse(parser, response.getId());
            currentDetectors.put(adID, new SimpleEntry<>(detector, clock.instant()));
            listener.onResponse(Optional.of(detector));
        } catch (Exception t) {
            LOG.error("Fail to parse detector {}", adID);
            LOG.error("Stack trace:", t);
            listener.onResponse(Optional.empty());
        }
    }, listener::onFailure);
}
 
Example 8
@Test
public void test_metadata() throws Exception {
    Path path = get(getClass().getResource("/docs/a/b/c/doc.txt").getPath());
    TikaDocument document = new Extractor().extract(path);

    spewer.write(document);

    GetResponse documentFields = es.client.get(new GetRequest(TEST_INDEX, "doc", document.getId()));
    assertThat(documentFields.getSourceAsMap()).includes(
            entry("contentEncoding", "ISO-8859-1"),
            entry("contentType", "text/plain"),
            entry("nerTags", new ArrayList<>()),
            entry("contentLength", 45),
            entry("status", "INDEXED"),
            entry("path", path.toString()),
            entry("dirname", path.getParent().toString())
    );
}
 
Example 9
Source Project: skywalking   Source File: UITemplateManagementEsDAO.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public TemplateChangeStatus addTemplate(final DashboardSetting setting) throws IOException {
    try {
        final UITemplate.Builder builder = new UITemplate.Builder();
        final UITemplate uiTemplate = setting.toEntity();

        final GetResponse response = getClient().get(UITemplate.INDEX_NAME, uiTemplate.id());
        if (response.isExists()) {
            return TemplateChangeStatus.builder().status(false).message("Template exists").build();
        }

        XContentBuilder xContentBuilder = map2builder(builder.data2Map(uiTemplate));
        getClient().forceInsert(UITemplate.INDEX_NAME, uiTemplate.id(), xContentBuilder);
        return TemplateChangeStatus.builder().status(true).build();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        return TemplateChangeStatus.builder().status(false).message("Can't add a new template").build();
    }
}
 
Example 10
Source Project: core-ng-project   Source File: ElasticSearchTypeImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Optional<T> get(GetRequest request) {
    var watch = new StopWatch();
    String index = request.index == null ? this.index : request.index;
    int hits = 0;
    try {
        var getRequest = new org.elasticsearch.action.get.GetRequest(index, request.id);
        GetResponse response = elasticSearch.client().get(getRequest, RequestOptions.DEFAULT);
        if (!response.isExists()) return Optional.empty();
        hits = 1;
        return Optional.of(mapper.fromJSON(response.getSourceAsBytes()));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        long elapsed = watch.elapsed();
        ActionLogContext.track("elasticsearch", elapsed, hits, 0);
        logger.debug("get, index={}, id={}, elapsed={}", index, request.id, elapsed);
        checkSlowOperation(elapsed);
    }
}
 
Example 11
@Test
public void testMGetResponse() throws Exception {
    
    String body = "{\"docs\":[{\"_index\":\"%1$s\",\"_type\":\"config\",\"_id\":\"0\",\"found\":true"
            + "},{\"_index\":\"%1$s\",\"_type\":\"config\","
            + "\"_id\":\"1\",\"found\":true}]}";
    MultiGetItemResponse [] items = new MultiGetItemResponse [2];
    for (int i = 0; i < items.length; i++) {
        String itemBody =  "{\"_index\":\"%1$s\",\"_type\":\"config\",\"_id\":\"" + i + "\",\"found\":true}";
        XContentParser parser = givenContentParser(itemBody);
        items[i] = new MultiGetItemResponse(GetResponse.fromXContent(parser), null);
    }
    
    MultiGetResponse actionResponse = new MultiGetResponse(items);
    
    OpenShiftRestResponse osResponse = whenCreatingResponseResponse(actionResponse);
    thenResponseShouldBeModified(osResponse, body);
}
 
Example 12
Source Project: pyramid   Source File: ESIndex.java    License: Apache License 2.0 6 votes vote down vote up
public Object getField(String id, String field){
        GetResponse response = client.prepareGet(this.indexName, this.documentType, id)
                .setFetchSource(field,null)
//                .setStoredFields(field)
                .execute()
                .actionGet();
        Object res = null;
        if (response==null){
            if (logger.isWarnEnabled()){
                logger.warn("no response from document "+id+" when fetching field "+field+"!");
            }
            return null;
        }else {
            res = response.getSourceAsMap().get(field);
            if (res==null){
                if (logger.isWarnEnabled()) {
                    logger.warn("document " + id + " has no field " + field + "!");
                }
            }
        }

        return res;
//        return response.getField(field).getValue();
    }
 
Example 13
Source Project: elasticsearch-taste   Source File: TasteSearchRestAction.java    License: Apache License 2.0 6 votes vote down vote up
private Map<String, Object> getObjectMap(final Client client,
        final String prefix, final String index, final String type,
        final String id) {
    try {
        return cache.get(prefix + id, () -> {
            final GetResponse response = client.prepareGet(index, type, id)
                    .execute().actionGet();
            if (response.isExists()) {
                return response.getSource();
            }
            return null;
        });
    } catch (final ExecutionException e) {
        throw new TasteException("Failed to get data for " + index + "/"
                + type + "/" + id, e);
    }
}
 
Example 14
Source Project: foxtrot   Source File: ElasticsearchConsolePersistence.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ConsoleV2 getV2(String id) {
    try {
        GetResponse result = connection.getClient()
                .prepareGet()
                .setIndex(INDEX_V2)
                .setType(TYPE)
                .setId(id)
                .execute()
                .actionGet();
        if (!result.isExists()) {
            return null;
        }
        return mapper.readValue(result.getSourceAsBytes(), ConsoleV2.class);
    } catch (Exception e) {
        throw new ConsolePersistenceException(id, "console get failed", e);
    }
}
 
Example 15
Source Project: conductor   Source File: ElasticSearchDAOV6.java    License: 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 16
Source Project: es-amazon-s3-river   Source File: S3River.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isStarted(){
   // Refresh index before querying it.
   client.admin().indices().prepareRefresh("_river").execute().actionGet();
   GetResponse isStartedGetResponse = client.prepareGet("_river", riverName().name(), "_s3status").execute().actionGet();
   try{
      if (!isStartedGetResponse.isExists()){
         XContentBuilder xb = jsonBuilder().startObject()
               .startObject("amazon-s3")
                  .field("feedname", feedDefinition.getFeedname())
                  .field("status", "STARTED").endObject()
               .endObject();
         client.prepareIndex("_river", riverName.name(), "_s3status").setSource(xb).execute();
         return true;
      } else {
         String status = (String)XContentMapValues.extractValue("amazon-s3.status", isStartedGetResponse.getSourceAsMap());
         if ("STOPPED".equals(status)){
            return false;
         }
      }
   } catch (Exception e){
      logger.warn("failed to get status for " + riverName().name() + ", throttling....", e);
   }
   return true;
}
 
Example 17
Source Project: conductor   Source File: ElasticSearchDAOV5.java    License: 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 18
Source Project: ProjectStudy   Source File: HighLevelRestController.java    License: MIT License 5 votes vote down vote up
/**
 * 根据ID查询
 *
 * @param id
 * @return com.example.common.ResponseBean
 * @throws IOException
 * @author wliduo[[email protected]]
 * @date 2019/8/15 14:10
 */
@GetMapping("/book/{id}")
public ResponseBean getById(@PathVariable("id") String id) throws IOException {
    // GetRequest
    GetRequest getRequest = new GetRequest(Constant.INDEX, id);
    // 查询ES
    GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
    BookDto bookDto = JSON.parseObject(getResponse.getSourceAsString(), BookDto.class);
    return new ResponseBean(HttpStatus.OK.value(), "查询成功", bookDto);
}
 
Example 19
public boolean documentExists(final String index, final String type, final String id) {
    return execute(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            LOGGER.trace("Checking for existence of document: '{}/{}/{}'", index, type, id);
            GetRequestBuilder builder = client.prepareGet().setIndex(index).setType(type).setId(id);
            GetResponse response = builder.get();
            final boolean exists = response.isExists();
            LOGGER.trace("Document '{}/{}/{}' exists? {}", index, type, id, exists);
            return exists;
        }
    });
}
 
Example 20
Source Project: camel-quarkus   Source File: ElasticsearchRestResource.java    License: Apache License 2.0 5 votes vote down vote up
@Path("/get")
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response getData(@QueryParam("indexId") String indexId) throws Exception {
    GetResponse response = producerTemplate
            .requestBody("elasticsearch-rest://elasticsearch?operation=GetById&indexName=test", indexId, GetResponse.class);

    if (response.getSource() == null) {
        return Response.status(404).build();
    }
    return Response.ok().entity(response.getSource().get("test-key")).build();
}
 
Example 21
Source Project: canal   Source File: UserSyncSingleTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 单表插入
 */
@Test
public void test01() {
    Dml dml = new Dml();
    dml.setDestination("example");
    dml.setTs(new Date().getTime());
    dml.setType("INSERT");
    dml.setDatabase("mytest");
    dml.setTable("user");
    List<Map<String, Object>> dataList = new ArrayList<>();
    Map<String, Object> data = new LinkedHashMap<>();
    dataList.add(data);
    data.put("id", 1L);
    data.put("name", "Eric");
    data.put("role_id", 1L);
    data.put("c_time", new Date());
    dml.setData(dataList);

    String database = dml.getDatabase();
    String table = dml.getTable();
    Map<String, ESSyncConfig> esSyncConfigs = esAdapter.getDbTableEsSyncConfig().get(database + "-" + table);

    esAdapter.getEsSyncService().sync(esSyncConfigs.values(), dml);

    GetResponse response = esAdapter.getEsConnection()
        .getTransportClient()
        .prepareGet("mytest_user", "_doc", "1")
        .get();
    Assert.assertEquals("Eric", response.getSource().get("_name"));
}
 
Example 22
Source Project: youkefu   Source File: ESDataExchangeImpl.java    License: Apache License 2.0 5 votes vote down vote up
public UKDataBean getIObjectByPK(UKDataBean dataBean , String id) {
	if(dataBean.getTable()!=null){
		GetResponse getResponse = UKDataContext.getTemplet().getClient()
				.prepareGet(UKDataContext.CALLOUT_INDEX,
						dataBean.getTable().getTablename(), dataBean.getId())
				.execute().actionGet();
		dataBean.setValues(getResponse.getSource());
		dataBean.setType(getResponse.getType());
	}else{
		dataBean.setValues(new HashMap<String,Object>());
	}
	
	return processDate(dataBean);
}
 
Example 23
Source Project: youkefu   Source File: ESDataExchangeImpl.java    License: Apache License 2.0 5 votes vote down vote up
public UKDataBean getIObjectByPK(String type , String id) {
	UKDataBean dataBean = new UKDataBean() ;
	if(!StringUtils.isBlank(type)){
		GetResponse getResponse = UKDataContext.getTemplet().getClient()
				.prepareGet(UKDataContext.CALLOUT_INDEX,
						type, id)
				.execute().actionGet();
		dataBean.setValues(getResponse.getSource());
		dataBean.setType(getResponse.getType());
		dataBean.setId(getResponse.getId());
	}else{
		dataBean.setValues(new HashMap<String,Object>());
	}
	return dataBean;
}
 
Example 24
Source Project: zeppelin   Source File: TransportBasedClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ActionResponse get(String index, String type, String id) {
  final GetResponse getResp = client
      .prepareGet(index, type, id)
      .get();

  return new ActionResponse()
      .succeeded(getResp.isExists())
      .hit(new HitWrapper(
          getResp.getIndex(),
          getResp.getType(),
          getResp.getId(),
          getResp.getSourceAsString()));
}
 
Example 25
Source Project: hsweb-learning   Source File: ElasticSearch.java    License: Apache License 2.0 5 votes vote down vote up
private static void MultiGet(Client client) {

        MultiGetResponse response = client.prepareMultiGet()
                .add("twitter","tweet","2","1")
                .get();
        for(MultiGetItemResponse itemResponse:response){
            GetResponse getResponse = itemResponse.getResponse();
            if(getResponse.isExists()){
                System.out.println(getResponse.getSourceAsString());
            }
        }
    }
 
Example 26
Source Project: springboot-learn   Source File: ElasticSearchController.java    License: MIT License 5 votes vote down vote up
@GetMapping("/get/book/novel")
public ResponseEntity get(@RequestParam(name = "id", defaultValue = "") String id) {
    if (id.isEmpty()) {
        return new ResponseEntity(HttpStatus.NOT_FOUND);
    }
    // 查询结果
    GetResponse result = transportClient.prepareGet(INDEX, TYPE, id)
            .get();
    if (!result.isExists()) {
        return new ResponseEntity(HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity(result.getSource(), HttpStatus.OK);
}
 
Example 27
Source Project: metacat   Source File: ElasticSearchUtilImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public ElasticSearchDoc get(final String type, final String id, final String index) {
    ElasticSearchDoc result = null;
    final GetResponse response = client.prepareGet(index, type, id).execute().actionGet(esCallTimeout);
    if (response.isExists()) {
        result = parse(response);
    }
    return result;
}
 
Example 28
private void onGetAnomalyDetectorResponse(GetResponse response) throws IOException {
    if (!response.isExists()) {
        XContentBuilder builder = channel
            .newErrorBuilder()
            .startObject()
            .field("Message", "AnomalyDetector is not found with id: " + detectorId)
            .endObject();
        channel.sendResponse(new BytesRestResponse(RestStatus.NOT_FOUND, response.toXContent(builder, EMPTY_PARAMS)));
        return;
    }

    searchAdInputIndices(detectorId);
}
 
Example 29
Source Project: anomaly-detection   Source File: ADStateManager.java    License: Apache License 2.0 5 votes vote down vote up
public void getAnomalyDetector(String adID, ActionListener<Optional<AnomalyDetector>> listener) {
    Entry<AnomalyDetector, Instant> detectorAndTime = currentDetectors.get(adID);
    if (detectorAndTime != null) {
        detectorAndTime.setValue(clock.instant());
        listener.onResponse(Optional.of(detectorAndTime.getKey()));
        return;
    }

    GetRequest request = new GetRequest(AnomalyDetector.ANOMALY_DETECTORS_INDEX, adID);

    clientUtil.<GetRequest, GetResponse>asyncRequest(request, client::get, onGetResponse(adID, listener));
}
 
Example 30
public <E extends StorableElement> E getAndParse(String name, Class<E> eltClass, String type) throws IOException {
    GetResponse response = internalGet(generateId(type, name)).get();
    if (response.isExists()) {
        return parse(eltClass, type, response.getSourceAsBytes());
    } else {
        return null;
    }
}