-1

我有以下映射,想知道如何使用 RestHighLevelClient 在 java 中编写相同的映射

{
  "mappings": {
    "properties": {
      "events": {
        "type": "nested",
        "properties": {
          "ecommerceData": {
            "type": "nested",
            "properties": {
              "comments": {
                "type": "nested",
                "properties": {
                  "recommendationType": {
                    "type": "keyword"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
4

1 回答 1

1

创建(嵌套)的最简单方法是将此映射放入JSON format文件中,然后以字符串格式读取它(提供的实用程序方法)并创建映射,如下所示:

这个官方文档中提到了其他方式。

创建一个名为的文件nested.mapping,我将使用它nested作为索引名称。

使用以下实用程序方法读取文件并以string格式返回

public String getStringFromFile(String fileName) throws IOException {
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();
        InputStream in = classLoader.getResourceAsStream(fileName); --> file name
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = in.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }
        return result.toString(StandardCharsets.UTF_8.name());
    }

使用上述实用方法创建索引的 Resthighlevelclient 代码

 if (!isIndexExist(client, indexName)) {
                JsonUtil jsonUtil = new JsonUtil();
                String indexString = jsonUtil.getStringFromFile(indexName + ".mapping");
                CreateIndexRequest request = new CreateIndexRequest(indexName);
                request.source(indexString, XContentType.JSON);
                client.indices().create(request, RequestOptions.DEFAULT);
            }

请查看我的 java 调试器屏幕截图,它以JSON格式正确读取此文件。

调试器代码图像

最后是 Elastic Mapping API 结果,显示索引创建成功。

{
  "nested": {
    "aliases": {

    },
    "mappings": {
      "properties": {
        "events": {
          "type": "nested",
          "properties": {
            "ecommerceData": {
              "type": "nested",
              "properties": {
                "comments": {
                  "type": "nested",
                  "properties": {
                    "recommendationType": {
                      "type": "keyword"
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
}
于 2020-04-11T16:17:58.533 回答