如何在Elasticsearch索引中插入数据

huangapple go评论93阅读模式
英文:

how to insert data in elastic search index

问题

我已创建一个名为 - test 的索引。并根据以下内容进行了映射:

{
   "test" : {
      "mappings" : {
         "properties" : {
            "name" : {
               "type" : "keyword"
            },
            "info" : {
               "type" : "nested"
            },
            "joining" : {
               "type" : "date"
            }
         }
      }
   }
}

如何编写一个 Java 代码,逐一向上述索引添加数据,或者建议示例或教程。

提前感谢。

英文:

i have created a index named - test. and as mapping as per following

{
 "test" : {
   "mappings" : {
      "properties" : {
          "name" : {
            "type" : "keyword"
          },
          "info" : {
             "type" : "nested"
          },
          "joining" : {
             "type" : "date"
          }
      }
   }
}

how to write a java code that adds data one by one to above index or suggest the example or tutorials

thanks in advance

答案1

得分: 1

下面是可以轻松用来索引数据的Java代码:您可以定义一个持有索引字段的JAVA POJO,就像下面的代码中UserRegistration是一个持有索引属性的POJO,然后您可以从Web服务或触发应用程序中的其他方法调用下面的方法来触发索引。

// ElasticSearch客户端
private RestHighLevelClient esclient = ...

// Jackson POJO-to-JSON映射器
private ObjectMapper objectMapper = new ObjectMapper();

public boolean register(UserRegistration userRegistration) throws IOException {
    final String userStr = objectMapper.writeValueAsString(userRegistration);
    final IndexRequest indexRequest = new IndexRequest(USERS_INDEX_NAME)
            .id(userRegistration.getUserId())
            .source(userStr, XContentType.JSON);
    IndexResponse indexResponse = esclient.index(indexRequest, RequestOptions.DEFAULT);
    return true;
}

请参考JAVA HLRC索引API客户端获取更多详情和代码示例。

英文:

Below is the java code which can be easily used to index the data:, you can define a JAVA POJO which holds your index fields, like in below code UserRegistration is a POJO holding the index props and than you can call below method from webservice or other methods which triggers indexing in your application.

// ElasticSearch client
private RestHighLevelClient esclient = ...


// Jackson POJO-to-JSON mapper
private ObjectMapper objectMapper = new ObjectMapper();

public boolean register(UserRegistration userRegistration) throws IOException {

		final String userStr = objectMapper.writeValueAsString(userRegistration);
		final IndexRequest indexRequest = new IndexRequest(USERS_INDEX_NAME)
				.id(userRegistration.getUserId())
				.source(userStr, XContentType.JSON);
		IndexResponse indexResponse = esclient.index(indexRequest, RequestOptions.DEFAULT);
		return true;
	}

Please refer JAVA HLRC index-api client for more details and code samples

huangapple
  • 本文由 发表于 2020年9月16日 18:32:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63918143.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定