org.elasticsearch.client.Client.index()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(11.4k)|赞(0)|评价(0)|浏览(167)

本文整理了Java中org.elasticsearch.client.Client.index()方法的一些代码示例,展示了Client.index()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Client.index()方法的具体详情如下:
包路径:org.elasticsearch.client.Client
类名称:Client
方法名:index

Client.index介绍

[英]Index a JSON source associated with a given index and type.

The id is optional, if it is not provided, one will be generated automatically.
[中]索引与给定索引和类型关联的JSON源。
id是可选的,如果未提供,将自动生成一个id。

代码示例

代码示例来源:origin: floragunncom/search-guard

public static void uploadFile(Client tc, String filepath, String index, String id) throws Exception {
  LOGGER.info("Will update '" + id + "' with " + filepath);
  try (Reader reader = new FileReader(filepath)) {
    final String res = tc
        .index(new IndexRequest(index).type("sg").id(id).setRefreshPolicy(RefreshPolicy.IMMEDIATE)
            .source(id, readXContent(reader, XContentType.YAML))).actionGet().getId();
    if (!id.equals(res)) {
      throw new Exception("   FAIL: Configuration for '" + id
          + "' failed for unknown reasons. Pls. consult logfile of elasticsearch");
    }
  } catch (Exception e) {
    throw e;
  }
}

代码示例来源:origin: Netflix/conductor

@Override
public void addMessage(String queue, Message message) {
  Map<String, Object> doc = new HashMap<>();
  doc.put("messageId", message.getId());
  doc.put("payload", message.getPayload());
  doc.put("queue", queue);
  doc.put("created", System.currentTimeMillis());
  IndexRequest request = new IndexRequest(logIndexName, MSG_DOC_TYPE);
  request.source(doc);
  try {
    new RetryUtil<>().retryOnException(
      () -> elasticSearchClient.index(request).actionGet(),
      null,
      null,
      RETRY_COUNT,
      "Indexing document in  for docType: message", "addMessage"
    );
  } catch (Exception e) {
    logger.error("Failed to index message: {}", message.getId(), e);
  }
}

代码示例来源:origin: floragunncom/search-guard

private static boolean uploadFile(final Client tc, final String filepath, final String index, final String _id, final boolean legacy) {
  
  String type = "sg";
  String id = _id;
      
  if(legacy) {
    type = _id;
    id = "0";
  }
  
  System.out.println("Will update '"+type+"/" + id + "' with " + filepath+" "+(legacy?"(legacy mode)":""));
  
  try (Reader reader = new FileReader(filepath)) {
    final String res = tc
        .index(new IndexRequest(index).type(type).id(id).setRefreshPolicy(RefreshPolicy.IMMEDIATE)
            .source(_id, readXContent(reader, XContentType.YAML))).actionGet().getId();
    if (id.equals(res)) {
      System.out.println("   SUCC: Configuration for '" + _id + "' created or updated");
      return true;
    } else {
      System.out.println("   FAIL: Configuration for '" + _id
          + "' failed for unknown reasons. Please consult the Elasticsearch logfile.");
    }
  } catch (Exception e) {
    System.out.println("   FAIL: Configuration for '" + _id + "' failed because of " + e.toString());
  }
  return false;
}

代码示例来源:origin: floragunncom/search-guard

private SearchGuardLicense createOrGetTrial(String msg) {
    long created = System.currentTimeMillis();
    ThreadContext threadContext = threadPool.getThreadContext();

    try(StoredContext ctx = threadContext.stashContext()) {
      threadContext.putHeader(ConfigConstants.SG_CONF_REQUEST_HEADER, "true");
      GetResponse get = client.prepareGet(searchguardIndex, "sg", "tattr").get();
      if(get.isExists()) {
        created = (long) get.getSource().get("val");
      } else {
        try {
          client.index(new IndexRequest(searchguardIndex)
          .type("sg")
          .id("tattr")
          .setRefreshPolicy(RefreshPolicy.IMMEDIATE)
          .create(true)
          .source("{\"val\": "+System.currentTimeMillis()+"}", XContentType.JSON)).actionGet();
        } catch (VersionConflictEngineException e) {
          //ignore
        } catch (Exception e) {
          LOGGER.error("Unable to index tattr", e);
        }
      }
    }

    return SearchGuardLicense.createTrialLicense(formatDate(created), clusterService, msg);
  }
}

代码示例来源:origin: javanna/elasticshell

@Override
protected ActionFuture<IndexResponse> doExecute(IndexRequest request) {
  return client.index(request);
}

代码示例来源:origin: mbok/logsniffer

@Override
  public IndexResponse execute(final Client client) {
    return client.index(indexRequest).actionGet();
  }
}).getId();

代码示例来源:origin: com.github.tlrx/elasticsearch-test

@Override
public Void execute(final Client client) throws ElasticsearchException {
  try {
    IndexResponse response = client.index(request).get();
  } catch (Exception e) {
    throw new EsSetupRuntimeException(e);
  }
  return null;
}

代码示例来源:origin: tlrx/elasticsearch-test

@Override
public Void execute(final Client client) throws ElasticsearchException {
  try {
    IndexResponse response = client.index(request).get();
  } catch (Exception e) {
    throw new EsSetupRuntimeException(e);
  }
  return null;
}

代码示例来源:origin: org.nuxeo.elasticsearch/nuxeo-elasticsearch-core

@Override
public IndexResponse index(IndexRequest request) {
  try {
    return client.index(request).actionGet();
  } catch (VersionConflictEngineException e) {
    throw new ConcurrentUpdateException(e);
  }
}

代码示例来源:origin: com.netflix.suro/suro-elasticsearch

@VisibleForTesting
protected void recover(int itemId, BulkRequest request) {
  client.index(createIndexRequest((Message) request.payloads().get(itemId))).actionGet();
}

代码示例来源:origin: com.floragunn/search-guard-6

private static boolean uploadFile(final Client tc, final String filepath, final String index, final String _id, final boolean legacy) {
  
  String type = "sg";
  String id = _id;
      
  if(legacy) {
    type = _id;
    id = "0";
  }
  
  System.out.println("Will update '"+type+"/" + id + "' with " + filepath+" "+(legacy?"(legacy mode)":""));
  
  try (Reader reader = new FileReader(filepath)) {
    final String res = tc
        .index(new IndexRequest(index).type(type).id(id).setRefreshPolicy(RefreshPolicy.IMMEDIATE)
            .source(_id, readXContent(reader, XContentType.YAML))).actionGet().getId();
    if (id.equals(res)) {
      System.out.println("   SUCC: Configuration for '" + _id + "' created or updated");
      return true;
    } else {
      System.out.println("   FAIL: Configuration for '" + _id
          + "' failed for unknown reasons. Please consult the Elasticsearch logfile.");
    }
  } catch (Exception e) {
    System.out.println("   FAIL: Configuration for '" + _id + "' failed because of " + e.toString());
  }
  return false;
}

代码示例来源:origin: com.floragunn/search-guard-6

public static void uploadFile(Client tc, String filepath, String index, String id) throws Exception {
  LOGGER.info("Will update '" + id + "' with " + filepath);
  try (Reader reader = new FileReader(filepath)) {
    final String res = tc
        .index(new IndexRequest(index).type("sg").id(id).setRefreshPolicy(RefreshPolicy.IMMEDIATE)
            .source(id, readXContent(reader, XContentType.YAML))).actionGet().getId();
    if (!id.equals(res)) {
      throw new Exception("   FAIL: Configuration for '" + id
          + "' failed for unknown reasons. Pls. consult logfile of elasticsearch");
    }
  } catch (Exception e) {
    throw e;
  }
}

代码示例来源:origin: spinscale/elasticsearch-river-streaming-json

private void storeLastUpdatedTimestamp(String exportTimestamp) {
  String json = "{ \"lastUpdatedTimestamp\" : \"" + exportTimestamp + "\" }";
  IndexRequest updateTimestampRequest = indexRequest(riverIndexName).type(riverName.name()).id("lastUpdatedTimestamp").source(json);
  client.index(updateTimestampRequest).actionGet();
}

代码示例来源:origin: ezbz/projectx

@Override
 public ActionFuture<IndexResponse> execute(final Client client) {
  final IndexRequest request = Requests.indexRequest(nodeTemplate.getIndexName())
                     .source(content).type("log");
  return client.index(request);
 }
});

代码示例来源:origin: com.floragunn/search-guard-6

private SearchGuardLicense createOrGetTrial(String msg) {
    long created = System.currentTimeMillis();
    ThreadContext threadContext = threadPool.getThreadContext();

    try(StoredContext ctx = threadContext.stashContext()) {
      threadContext.putHeader(ConfigConstants.SG_CONF_REQUEST_HEADER, "true");
      GetResponse get = client.prepareGet(searchguardIndex, "sg", "tattr").get();
      if(get.isExists()) {
        created = (long) get.getSource().get("val");
      } else {
        try {
          client.index(new IndexRequest(searchguardIndex)
          .type("sg")
          .id("tattr")
          .setRefreshPolicy(RefreshPolicy.IMMEDIATE)
          .create(true)
          .source("{\"val\": "+System.currentTimeMillis()+"}", XContentType.JSON)).actionGet();
        } catch (VersionConflictEngineException e) {
          //ignore
        } catch (Exception e) {
          LOGGER.error("Unable to index tattr", e);
        }
      }
    }

    return SearchGuardLicense.createTrialLicense(formatDate(created), clusterService, msg);
  }
}

代码示例来源:origin: eclipse/kapua

@Override
public InsertResponse insert(InsertRequest insertRequest) throws ClientException {
  checkClient();
  Map<String, Object> storableMap = modelContext.marshal(insertRequest.getStorable());
  logger.debug("Insert - converted object: '{}'", storableMap);
  org.elasticsearch.action.index.IndexRequest idxRequest = new org.elasticsearch.action.index.IndexRequest(insertRequest.getTypeDescriptor().getIndex(), insertRequest.getTypeDescriptor().getType()).source(storableMap);
  if (insertRequest.getId() != null) {
    idxRequest.id(insertRequest.getId()).version(1).versionType(VersionType.EXTERNAL);
  }
  org.elasticsearch.action.index.IndexResponse response = esClientProvider.getClient().index(idxRequest).actionGet(getQueryTimeout());
  return new InsertResponse(response.getId(), insertRequest.getTypeDescriptor());
}

代码示例来源:origin: org.eclipse.kapua/kapua-datastore-client-transport

@Override
public InsertResponse insert(InsertRequest insertRequest) throws ClientException {
  checkClient();
  Map<String, Object> storableMap = modelContext.marshal(insertRequest.getStorable());
  logger.debug("Insert - converted object: '{}'", storableMap);
  org.elasticsearch.action.index.IndexRequest idxRequest = new org.elasticsearch.action.index.IndexRequest(insertRequest.getTypeDescriptor().getIndex(), insertRequest.getTypeDescriptor().getType()).source(storableMap);
  if (insertRequest.getId() != null) {
    idxRequest.id(insertRequest.getId()).version(1).versionType(VersionType.EXTERNAL);
  }
  org.elasticsearch.action.index.IndexResponse response = esClientProvider.getClient().index(idxRequest).actionGet(getQueryTimeout());
  return new InsertResponse(response.getId(), insertRequest.getTypeDescriptor());
}

代码示例来源:origin: harbby/presto-connectors

public void putScriptToIndex(PutIndexedScriptRequest request, ActionListener<IndexResponse> listener) {
  String scriptLang = validateScriptLanguage(request.scriptLang());
  //verify that the script compiles
  validate(request.source(), scriptLang);
  IndexRequest indexRequest = new IndexRequest(request).index(SCRIPT_INDEX).type(scriptLang).id(request.id())
      .version(request.version()).versionType(request.versionType())
      .source(request.source()).opType(request.opType()).refresh(true); //Always refresh after indexing a template
  client.index(indexRequest, listener);
}

代码示例来源:origin: salyh/elasticsearch-imap

@Override
public void onMessage(final Message msg) throws IOException, MessagingException {
  if (closed) {
    if (logger.isTraceEnabled()) {
      logger.trace("Is closed, will not index");
    }
    return;
  }
  if (isError()) {
    if (logger.isTraceEnabled()) {
      logger.trace("error, not indexing");
    }
    return;
  }
  
  createIndexIfNotExists();
  final IndexableMailMessage imsg = IndexableMailMessage.fromJavaMailMessage(msg, withTextContent, withHtmlContent, preferHtmlContent, withAttachments,
      stripTagsFromTextContent, headersToFields);
  if (logger.isTraceEnabled()) {
    logger.trace("Process mail " + imsg.getUid() + "/" + imsg.getPopId() + " :: " + imsg.getSubject() + "/" + imsg.getSentDate());
  }
  client.index(createIndexRequest(imsg)).actionGet();
}

代码示例来源:origin: harbby/presto-connectors

indexRequest.consistencyLevel(WriteConsistencyLevel.fromString(consistencyLevel));
client.index(indexRequest, new RestBuilderListener<IndexResponse>(channel) {
  @Override
  public RestResponse buildResponse(IndexResponse response, XContentBuilder builder) throws Exception {

相关文章