如何使用rails上的搜索踢来搜索存储在jsonb字段中的记录

问题描述 投票:0回答:1

我在 products 中有 jsonb 字段 ocr_extract,并且我有一个搜索输入,应该通过 ocr_extract[:text] 字段查询产品。

数据存储在 ocr_extract 字段中,格式如下:

ocr_extract:
   "[{\"text\": \"raa\", \"x\": 550, \"y\": 195, \"w\": 19, \"h\": 3}, \n                       {\"text\": \"ee\", \"x\": 570, \"y\": 194, \"w\": 134, \"h\": 8}, \n                       {\"text\": \"sinter\", \"x\": 752, \"y\": 193, \"w\": 76, \"h\": 9}, \n                       {\"text\": \"aoe\", \"x\": 806, \"y\": 180, \"w\": 17, \"h\": 6}, \n                       {\"text\": \"3se\", \"x\": 853, \"y\": 195, \"w\": 137, \"h\": 3}, \n                       {\"text\": \"mr\", \"x\": 991, \"y\": 195, \"w\": 52, \"h\": 3}, \n                       {\"text\": \"sea\", \"x\": 636, \"y\": 216, \"w\": 17, \"h\": 6}, \n                       {\"text\": \"2\", \"x\": 763, \"y\": 208, \"w\": 13, \"h\": 6}, \n                       {\"text\": \"=\", \"x\": 804, \"y\": 216, \"w\": 10, \"h\": 6}, \n                       {\"text\": \"16\", \"x\": 962, \"y\": 216, \"w\": 17, \"h\": 6}]" 

这就是我的代码的样子:

产品.rb

searchkick index_name: "products"

  def search_data
    {
      id: self.id,
      ocr_extract: self.ocr_extract,
      created_at: self.created_at
    }
  end

产品控制器.rb

Product.search(query, fields: [:ocr_extract], match: :word_middle)
ruby-on-rails elasticsearch searchkick
1个回答
0
投票

问题很老,但在我的搜索结果中排在第一位,因此这可能对其他人有帮助。

我有一个场景,我想使用 Mobility Gem 将翻译作为 jsonb 列存储在数据库中,并使其可搜索,无论用户区域设置如何。 因此,关于动物模型,该列看起来像

name: {"en"=>"dog", "fr"=>"chien"}

如果您的目标是简单地搜索与当前存储的所有可能翻译匹配的

Animal
名称,您可以按照此答案 Searchkick word_start 与嵌套字段匹配

现在你的动物类看起来像这样

class Animal < ApplicationRecord
  extend Mobility
  translates :name, fallbacks: { fr: :en }

  searchkick

  def search_data
    {
      # Indexes as an array of values with the stored translations
      name: JSON.parse(name_for_database).values 
    }
  end
end

重新索引动物模型后,您可以搜索它,期望与任何可用的翻译相匹配:

Animal.search("dog")
=> #<Searchkick::Relation [#<Animal id: 2, name: {"en"=>"dog", "fr"=>"chien"}, created_at: "2024-03-29 04:09:54.463595000 +0000", updated_at: "2024-03-29 04:43:27.339374000 +0000">]>

Animal.search("chien")
=> #<Searchkick::Relation [#<Animal id: 2, name: {"en"=>"dog", "fr"=>"chien"}, created_at: "2024-03-29 04:09:54.463595000 +0000", updated_at: "2024-03-29 04:43:27.339374000 +0000">]>

Animal.search("cane")
=> #<Searchkick::Relation []>
© www.soinside.com 2019 - 2024. All rights reserved.