太阳黑子 Gem 在 STI 中使用 TABLE

Sunspot Gem Using in STI TABLE

我有Account型号,AssetCapitalRevenue这个table都继承了我的Account型号。我的帐户模型中有 3 种属性。名称、代码和类型。当我创建一个帐户时,将在我的帐户中插入一个,另一个在我的类型中,例如

Account.create(name: "test123", code:"test123", type:"Asset")

sql 将 运行 两个插入一个用于帐户模型,一个用于资产 Table

我的太阳黑子运行良好,它将 重新索引 我的数据库,我可以搜索我的参数

但是当我更新我的模型帐户时,我的 sql 运行 一次插入和一次更新

我的问题是如何在更新时重新索引我的模型。与特定数据。我可以做到 Sunspot.reindex,但这会加载我的 sql 中的所有数据。那会让我变慢

根据 the documentation,如果您在 Rails,对象将被自动索引。但它也提到您可以手动重新索引 class:

Account.reindex
Sunspot.commit

它还建议对单个对象使用 Sunspot.index

sql will run Two Insert one for Account model and one for Asset Table

仅供参考,当你想在多个模型之间共享同一个数据库时使用 STI table,因为它们的属性和行为相似。像 AdminUser 模型可能具有与 PublisherUserReaderUser 几乎相同的 attributes/columns。因此,您可能希望有一个名为 users 或模型 User 的通用 table,并在上述模型中共享此 table。

Point 是:ActiveRecord 将 运行 单个 SQL 查询而不是两个,例如:

INSERT INTO "accounts" ("name", "code", "type") VALUES ('test123', 'test123', 'Asset')

my question is how can i reindex my model when i update. with a particular data. i can do Sunspot.reindex but this is will load all data in my sql. that will cause me to slow

实际上 sunspot_rails 设计为在您对 model/record 进行更改时自动重建索引。它监听 save callbacks.

但是你需要确保你没有使用像update_column(s)这样的方法。 See the list of silent create/update methods which do not trigger callbacks and validations at all.


另外,你需要理解Solr中batch size的概念。出于性能原因,您的所有新索引都不会立即提交。 Committed 意味着,像 RDBMS 提交一样将索引写入数据库。

默认情况下,提交的 batch_size50。这意味着在执行 50 index 次方法后,只有索引会被提交,您将能够搜索记录。要更改它,请使用以下

# in config/initializers/sunspot_config.rb
Sunspot.config.indexing.default_batch_size = 1 # or any number

# in models; its not considered good though
after_commit do
  Sunspot.commit
end

对于手动重新索引,您可以使用 建议的方法。

但是,我认为您不需要干预自动操作。我认为您没有看到立竿见影的效果,所以您很担心。

我把它放到我的模型中

 after_update do
  Sunspot.index Account.where(id: self.id)
end