【问题标题】:Spring data elasticsearch to create index dynamically based on request parameter, percolator support and create index via Elasticsearch OperationsSpring data elasticsearch 根据请求参数动态创建索引,过滤器支持并通过 Elasticsearch Operations 创建索引
【发布时间】:2021-08-15 14:37:14
【问题描述】:

我从https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#reference开始阅读

我的要求

  1. 我想使用过滤器。在 spring data elasticsearch 中是否有任何支持?我在上面的链接中看不到任何内容,尽管我知道渗透与索引相同(从技术上讲,从使用 spring data elasticsearch 的角度来看)。所以我可以使用 spring data elasticsearch 的索引部分,但只是检查是否有任何特定于 percolator 的部分。
  2. 我想动态创建索引。我明白我可以使用 https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.mapping.meta-model.annotations 中提到的 SpEL 模板表达式来实现这一点,但我的情况略有不同,我将通过 RequestParam 作为 API 调用的一部分获取索引名称。所以这意味着据我所知,我不能使用 SpEL 或尝试类似https://stackoverflow.com/a/33520421/4068218
  3. 我知道我可以使用 ElasticsearchOperations 或 ElasticsearchRepository 创建索引。由于#2(即通过请求参数的索引名称),我认为 ElasticsearchOperations 更适合,但我看到 IndexOperations 促进 createMapping、createSettings 但不能同时使用。我也看到了 putMapping,但我没有看到任何同时说明映射和设置的内容。我想要两者的原因是我想创建如下所示的内容
  "settings" : {
                "index" : {
                  "number_of_shards" : 1,
                  "number_of_replicas" : 0
                }
              },
            "mappings": {
                "properties": {
                  "message": {
                    "type": "text"
                  },
                  "query": {
                    "type": "percolator"
                  }
                }
              }

底线:- 如何使用 ElasticsearchOperations 的映射和设置创建索引(索引名称将通过请求参数动态变化)?
非常感谢任何线索/帮助

【问题讨论】:

  • IndexOperations.createWithMapping() 从当前版本 4.2.0 开始可以在一次调用中创建包含设置和映射的索引
  • @P.J.Meisch - 感谢您的回复和您的时间。由于我希望索引名称是动态的(即我接受作为 API 端点中的参数),我将无法使用任何需要 @Document(indexName = "name-of-the-index") 的类。
  • elasticsearchOperations.indexOps(IndexCoordinates.of("whatever-indexname-you-need")).create(settings, mapping)

标签: java spring-boot elasticsearch spring-data-elasticsearch


【解决方案1】:

首先非常感谢@P.J.Meisch。为您的两位 cmets 投票以表示感谢。

以下对我有用。以下可能会在将来对其他人有所帮助

 Document mapping = Document.create().fromJson("{\n" +
                "\n" +
                "    \"properties\": {\n" +
                "      \"message\": {\n" +
                "        \"type\": \"text\"\n" +
                "      },\n" +
                "      \"query\": {\n" +
                "        \"type\": \"percolator\"\n" +
                "      }\n" +
                "    }\n" +
                "\n" +
                "}");
 Map<String, Object> settings = ImmutableMap.of( "number_of_shards" ,2,"number_of_replicas",1);
 elasticsearchOperations.indexOps(IndexCoordinates.of("whatever-indexname-you-need")).create(settings,mapping);

【讨论】:

  • 这对我帮助很大,非常感谢!作为旁注,我认为使用 Document.from(Map) 比使用字符串化 JSON 更好
猜你喜欢
  • 1970-01-01
  • 2016-11-01
  • 2017-12-17
  • 2015-05-15
  • 2013-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-04
相关资源
最近更新 更多