SkillAgentSearch skills...

Searchcraft

Instant Search for Rails and ActiveRecord using SQL materialized views

Install / Use

/learn @drnic/Searchcraft
About this skill

Quality Score

0/100

Supported Platforms

Zed

README

<picture> <source media="(prefers-color-scheme: dark)" srcset="https://github.com/drnic/searchcraft/blob/develop/docs/searchcraft-logo-white.png?raw=true"> <source media="(prefers-color-scheme: light)" srcset="https://github.com/drnic/searchcraft/blob/develop/docs/searchcraft-logo-black.png?raw=true"> <img src="https://github.com/drnic/searchcraft/blob/develop/docs/searchcraft-logo-on-white.png?raw=true"> </picture>

Instant search for Rails and ActiveRecord using SQL materialized views.

  • 10x speed improvements to homepages and dashboards
  • Native Rails replacement for ElasticSearch
  • Create reporting and summary tables that are easily updatable and queryable

See demo app (code found in demo_app/ folder):

searchcraft 10x speed demo

Introduction

Add lightning quick search capabilities to your Rails apps without external systems like ElasticSearch. It's now magically simple to craft the ActiveRecord/Arel expressions we already know and love, and convert them into SQL materialized views: ready to be queried and composed with ActiveRecord. Everything you love about Rails, but faster.

What makes Rails slow for search? Large tables, lots of joins, subqueries, missing or unused indexes, and complex queries. Also slow? Coordinating data from multiple external systems through Ruby to produce search results.

SearchCraft makes it trivial to write and use powerful SQL materialized views to pre-calculate the results of your search and reporting queries. It's like a database index, but for complex queries.

Materialized views are a wonderful feature of PostgreSQL, Oracle, and SQL Server*. They are a table of pre-calculated results of a query. They are fast to query. They are awesome. Like other search systems, you control when you want to refresh them with new data.

Inside Rails and ActiveRecord, you can access a read-only materialized view like you would any regular table. You can even join them together. You can use them in your ActiveRecord models, scopes, and associations.

class ProductSearch < ActiveRecord::Base
  include SearchCraft::Model
end

Done. Whatever columns you describe in your view will become attributes on your model.

If the underlying view had columns product_id, product_name, reviews_count, and reviews_average, then you can query it like any other ActiveRecord model:

ProductSearch.all
[#<ProductSearch product_id: 2, product_name: "iPhone 15", reviews_count: 5, reviews_average: 0.38e1>,
 #<ProductSearch product_id: 1, product_name: "Laptop 3", reviews_count: 5, reviews_average: 0.28e1>,
 #<ProductSearch product_id: 4, product_name: "Monopoly", reviews_count: 3, reviews_average: 0.2e1>]

ProductSearch.order(reviews_average: :desc)
[#<ProductSearch product_id: 2, product_name: "iPhone 15", reviews_count: 5, reviews_average: 0.38e1>,
   #<ProductSearch product_id: 1, product_name: "Laptop 3", reviews_count: 5, reviews_average: 0.28e1>,
   #<ProductSearch product_id: 4, product_name: "Monopoly", reviews_count: 3, reviews_average: 0.2e1>]

If you include foreign keys, then you can use belongs_to associations. You can add scopes. You can add methods. You can use it as the starting point for queries with the rest of your SQL database. It's just a regular ActiveRecord model.

All this is already possible with Rails and ActiveRecord. SearchCraft achievement is to make it trivial to live with your materialized views. Trivial to refresh them and to write them.

Refresh materialized views

Each SearchCraft materialized view a snapshot of the results of the query at the time it was created, or last refreshed. It's like a table whose contents are derived from a query.

If the underlying data to your SearchCraft materialized view changes and you want to refresh it, then call refresh! on your model class. This is provided by the SearchCraft::Model mixin.

ProductSearch.refresh!

You can pass this ActiveRecord relation/array to your Rails views and render them. You can join it to other tables and apply further scopes.

Writing and iterating on materialized views

But SearchCraft's greatest feature is help you write your materialized views, and then to iterate on them.

Design them in ActiveRecord expressions, Arel expressions, or even plain SQL. No migrations to rollback and re-run. No keeping track of whether the SQL view in your database matches the SearchCraft code in your Rails app. SearchCraft will automatically create and update your materialized views.

Update your SearchCraft view, run your tests, they work. Update your SearchCraft view, refresh your development app, and it works. Open up rails console and it works; then update your view, type reload!, and it works. Deploy to production anywhere, and it works.

Write views in ActiveRecord or Arel

What does it look like to design a materialized view with SearchCraft? For our ProductSearch model above, we create a ProductSearchBuilder class that inherits from SearchCraft::Builder and provides either a view_scope method or view_select_sql method.

class ProductSearchBuilder < SearchCraft::Builder
  def view_scope
    Product.where(active: true)
      .select(
        "products.id AS product_id",
        "products.name AS product_name",
        "(SELECT COUNT(*) FROM product_reviews WHERE product_reviews.product_id = products.id) AS reviews_count",
        "(SELECT AVG(rating) FROM product_reviews WHERE product_reviews.product_id = products.id) AS reviews_average"
      )
  end
end

The view_scope method must return an ActiveRecord relation. It can be as simple or as complex as you like. It can use joins, subqueries, and anything else you can do with ActiveRecord. In the example above we:

  • filter out inactive products
  • select the id and name columns from the products table; where we can later use product_id as a foreign key for joins to the Product model in our app
  • build new reviews_count and reviews_average columns using SQL subqueries that counts and averages the rating column from the product_reviews table.

SearchCraft will convert this into a materialized view, create it into your database, and the ProductSearch model above will start using it when you next reload your development app or run your tests. If you make a change, SearchCraft will drop and recreate the view automatically.

When we load up our app into Rails console, or run our tests, or refresh the development app, the ProductSearch model will be automatically updated to match any changes in ProductSearchBuilder.

ProductSearch.all
  [#<ProductSearch product_id: 2, product_name: "iPhone 15", reviews_count: 5, reviews_average: 0.38e1>,
   #<ProductSearch product_id: 1, product_name: "Laptop 3", reviews_count: 5, reviews_average: 0.28e1>,
   #<ProductSearch product_id: 4, product_name: "Monopoly", reviews_count: 3, reviews_average: 0.2e1>]

ProductSearch.order(reviews_average: :desc)
  [#<ProductSearch product_id: 2, product_name: "iPhone 15", reviews_count: 5, reviews_average: 0.38e1>,
   #<ProductSearch product_id: 1, product_name: "Laptop 3", reviews_count: 5, reviews_average: 0.28e1>,
   #<ProductSearch product_id: 4, product_name: "Monopoly", reviews_count: 3, reviews_average: 0.2e1>]

Write views in SQL

If you want to write SQL, then you can use the view_select_sql method instead.

class NumberBuilder < SearchCraft::Builder
  # Write SQL that produces 5 rows, with a 'number' column containing the number of the row
  def view_select_sql
    "SELECT generate_series(1, 5) AS number;"
  end
end

class Number < ActiveRecord::Base
  include SearchCraft::Model
end
Number.all
[#<Number number: 1>, #<Number number: 2>, #<Number number: 3>, #<Number number: 4>, #<Number number: 5>]

Indexes

A wonderful feature of materialized views is you can add indexes to them; even unique indexes.

Currently the mechanism for adding indexes is to add a view_indexes method to your builder class.

For example, we can add a unique index on NumberBuilder's number column:

class NumberBuilder < SearchCraft::Builder
  def view_indexes
    {
      number: {columns: ["number"], unique: true}
    }
  end

Or several indexes on the ProductSearchBuilder from earlier:

class ProductSearchBuilder < SearchCraft::Builder
  def view_indexes
    {
      id: {columns: ["product_id"], unique: true},
      product_name: {columns: ["product_name"]},
      reviews_count: {columns: ["reviews_count"]},
      reviews_average: {columns: ["reviews_average"]}
    }
  end
end

By default the indexes will be using: :btree indexing method. You can also use other indexing methods available in rails, such as :gin, :gist, or if you're using the trigram extension you can use :gin_trgm_ops. These can be useful when you're looking at setting up text search, as discussed below.

Search

Another benefit of materialized views is we can create columns that are optimised for search. For example above, since we've precalculated the reviews_average in ProductSearchBuilder, we can easily find products with a certain average rating.

ProductSearch.where("reviews_average > 4")

Associations

A fabulous feature of ActiveRecord is the ability to join queries together. Since our materialized views are native ActiveRecord models, we can join them together with other queries.

Let's setup an association between our MV's ProductSearch#product_id and the table Product#id primary key:

class ProductSearch < ActiveRecord::Base
  include SearchCraft::Model

  belongs_to :product, foreign_key: :product_id, primary_key: :id
end

We can now join, or eager load, the tables together with ActiveRecord queries. To followin

Related Skills

View on GitHub
GitHub Stars110
CategoryData
Updated3mo ago
Forks1

Languages

Ruby

Security Score

97/100

Audited on Dec 3, 2025

No findings