【问题标题】:rails elasticsearch searching a nested json fieldrails elasticsearch搜索嵌套的json字段
【发布时间】:2015-07-23 16:25:53
【问题描述】:

我将 elasticsearch-model gem 用于具有has_many 关系的模型。为了匹配文档,假设模型是Article,关系是has_many categories。所以我将客户序列化程序编写如下(直接来自文档):

def as_indexed_json(options={})
  self.as_json(
    include: { categories: { only: :title},
             })
end

序列化似乎有效。示例文章的 as_indexed_json 的结果包含一个 "categories" => {"title"=> "one", "title"=> "two", "title"=> "three"} 块。

我正在苦苦挣扎并且无法在文档中找到的是如何搜索这个嵌套字段。

这是我尝试过的:

elasticsearch documentation on nested query 我想它应该是这样的:

r = Article.search query: {
    nested: {
        path: "categories",
        query: {match: {title: "one"}}
    }
}

但是当我执行r.results.first 时,我得到一个错误:nested object under path [categories] is not of nested type]...

我尝试添加将序列化程序中的一行更改为:include: { categories: { type: "nested", only: :title},但这并没有改变任何东西,它仍然说类别不是嵌套类型。

当然,我也试过像这样只查询没有任何嵌套的字段:

r = Article.search query: {match: {categories: 'one'}}

但这不会返回任何结果。

全文搜索如下:

r = Article.search query: {match: {_all: 'one'}}

返回结果,但我当然只想在类别字段中搜索“一个”。

任何帮助将不胜感激!

【问题讨论】:

    标签: ruby-on-rails elasticsearch elasticsearch-model


    【解决方案1】:

    Rails 不会在 elasticsearch 中创建嵌套映射。 Elasticsearch 正在使用动态映射将类别作为对象而不是嵌套子项(“当 Elasticsearch 在文档中遇到以前未知的字段时,它会使用动态映射来确定该字段的数据类型,并自动将新字段添加到类型映射中作为对象而不嵌套它们”)。为了使它们成为嵌套对象,您需要在 elasticsearch 中再次创建映射,并将类别作为嵌套类型,注意类型作为类别的嵌套。

     PUT /my_index 
    {
      "mappings": {
        "article": {
          "properties": {
            "categories": {
              "type": "nested", 
              "properties": {
                "name":    { "type": "string"  },
                "comment": { "type": "string"  },
                "age":     { "type": "short"   },
                "stars":   { "type": "short"   },
                "date":    { "type": "date"    }
              }
            }
          }
        }
      }
    }
    

    在此之后,您可以重新索引来自客户端的数据,或者如果您希望零停机时间阅读 here

    P.S:在创建新索引之前,您必须删除特定索引的旧映射。

    【讨论】:

      【解决方案2】:

      好的,所以它看起来像:r = Article.search query: {match: {"categories.title" => 'one'}} 有效,但我会留下问题,以防有人可以解释嵌套的东西发生了什么......

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多