Elasticsearch-向CreateIndexResponse添加类型和ID

时间:2016-08-27 10:28:16

标签: elasticsearch elasticsearch-java-api

创建索引时,可以使用:

type

但是,如何设置索引id以及只有一个title字段的此一个源对象的IndexAlreadyExistsException

修改

如果按照建议更改以添加两个文档,我会不断收到CreateIndexResponse createIndexRequestBuilder = client().admin().indices() .prepareCreate(INDEX_NAME) .setSettings( Settings.settingsBuilder() .put("index.number_of_shards", 2) .put("index.number_of_replicas", 2) ) .execute() .actionGet(); IndexResponse response1 = client().prepareIndex(INDEX_NAME, BOOK_TYPE_NAME, "id1") .setSource(XContentFactory.jsonBuilder() .startObject() .field("title", "Clean COde") .endObject() ) .setRouting("route1") .get(); IndexResponse response2 = client().prepareIndex(INDEX_NAME, BOOK_TYPE_NAME, "id2") .setSource(XContentFactory.jsonBuilder() .startObject() .field("title", "Learn Scala") .endObject() ) .setRouting("route2") .get(); 错误:

prepareCreate

似乎prepareIndex# clone your main repo $ git clone https://github.com/USERNAME/REPOSITORY-NAME $ cd REPOSITORY-NAME # do the actual subtree split $ git filter-branch --prune-empty --subdirectory-filter FOLDER-NAME BRANCH-NAME # push to the subtree split repo $ git remote set-url origin https://github.com/USERNAME/NEW-REPOSITORY-NAME.git $ git push -u origin BRANCH-NAME 都创建了索引。但不允许设置所有必需的首选项含义:

  • shard nr
  • replica nr
  • 索引名称
  • 索引类型
  • 新文件ID。
  •   -

如何做到这一点?

1 个答案:

答案 0 :(得分:0)

根据您提供的代码,您似乎正在尝试使用客户端管理API来创建索引,以尝试创建索引并同时索引文档。 admin()。indices()API用于管理索引作为一个整体,而不是用于索引,创建,删除等文档到/从索引。

您可以使用代码创建索引,并删除setSource部分。

为了实际索引文档,请参阅此处:https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-docs-index.html

具体来说,这段代码:

IndexResponse response = client.prepareIndex("twitter", "tweet", "1")
    .setSource(jsonBuilder()
                .startObject()
                    .field("user", "kimchy")
                    .field("postDate", new Date())
                    .field("message", "trying out Elasticsearch")
                .endObject()
              )
    .get();

prepareIndex()的参数1和2分别是索引名称和文档类型,而可选的第3个参数用于提供ID,这正是您要查找的内容。

我将如何做到这一点:

IndicesExistsResponse res = client.admin().indices().prepareExists("twitter").get();

if (!res.isExists()) {
    System.out.println("index doesn't exist, creating");
    CreateIndexResponse createIndexRequestBuilder = client.admin().indices()
            .prepareCreate("twitter")
            .setSettings(
                    Settings.settingsBuilder()
                            .put("index.number_of_shards", 2)
                            .put("index.number_of_replicas", 2)
            )
            .get()
}

IndexResponse response = client.prepareIndex("twitter", "tweet", "1")
    .setSource(jsonBuilder()
                .startObject()
                    .field("user", "kimchy")
                    .field("postDate", new Date())
                    .field("message", "trying out Elasticsearch")
                .endObject()
              )
    .get();