Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

search_cop

> 数据库
Open source

Search engine like fulltext query support for ActiveRecord

838 stars0 likes1 views
WebsiteGitHub

About

Search engine like fulltext query support for ActiveRecord

SearchCop

SearchCop extends your ActiveRecord models to support fulltext search engine like queries via simple query strings and hash-based queries. Assume you have a Book model having various attributes like title, author, stock, price, available. Using SearchCop you can perform:

…

where context is a json/jsonb column which e.g. contains:

json
{
  "browser": {
    "user_agent": "Firefox ..."
  }
}

Fulltext index capabilities

By default, i.e. if you don't tell SearchCop about your fulltext indices, SearchCop will use LIKE '%...%' queries. Unfortunately, unless you create a trigram index (postgres only), these queries can not use SQL indices, such that every row needs to be scanned by your RDBMS when you search for Book.search("Harry Potter") or similar. To avoid the penalty of LIKE queries, SearchCop can exploit the fulltext index capabilities of MySQL and PostgreSQL. To use already existing fulltext indices, simply tell SearchCop to use them via:

ruby
class Book  :fulltext
    options :author, :type => :fulltext
  end

  # ...
end

SearchCop will then transparently change its SQL queries for the attributes having fulltext indices to:

…

Obviously, these queries won't always return the same results as wildcard LIKE queries, because we search for words instead of sub-strings. However, fulltext indices will usually of course provide better performance.

Moreover, the query above is not yet perfect. To improve it even more, SearchCop tries to optimize the queries to make optimal use of fulltext indices while still allowing to mix them with non-fulltext attributes. To improve queries even more, you can group attributes and specify a default field to search in, such that SearchCop must no longer search within all fields:

ruby
search_scope :search do
  attributes all: [:author, :title]

  options :all, :type => :fulltext, default: true

  # Use default: true to explicitly enable fields as default fields (whitelist approach)
  # Use default: false to explicitly disable fields as default fields (blacklist approach)
end

Now SearchCop can optimize the following, not yet optimal query:

…

to the following, more performant query:

ruby
Book.search("Rowling OR Tolkien stock > 1")
# MySQL: ... WHERE MATCH(books.author, books.title) AGAINST('Rowling Tolkien' IN BOOLEAN MODE) AND books.stock > 1
# PostgreSQL: ... WHERE to_tsvector('simple', books.author || ' ' || books.title) @@ to_tsquery('simple', 'Rowling | Tokien') and books.stock > 1

What is happening here? Well, we specified all as the name of an attribute group that consists of author and title. As we, in addition, specified all to be a fulltext attribute, SearchCop assumes there is a compound fulltext index present on author and title, such that the query is optimized accordingly. Finally, we specified all to be the default attribute to search in, such that SearchCop can ignore other attributes, like e.g. stock, as long as they are not specified within queries directly (like for stock > 0).

Other queries will be optimized in a similar way, such that SearchCop tries to minimize the fultext constraints within a query, namely MATCH() AGAINST() for MySQL and to_tsvector() @@ to_tsquery() for PostgreSQL.

ruby
Book.search("(Rowling -Potter) OR Tolkien")
# MySQL: ... WHERE MATCH(books.author, books.title) AGAINST('(+Rowling -Potter) Tolkien' IN BOOLEAN MODE)
# PostgreSQL: ... WHERE to_tsvector('simple', books.author || ' ' || books.title) @@ to_tsquery('simple', '(Rowling & !Potter) | Tolkien')

To create a fulltext index on books.title in MySQL, simply use:

ruby
add_index :books, :title, :type => :fulltext

Regarding compound indices, which will e.g. be used for the default field all we already specified above, use:

ruby
add_index :books, [:author, :title], :type => :fulltext

Please note that MySQL supports fulltext indices for MyISAM and, as of MySQL version 5.6+, for InnoDB as well. For more details about MySQL fulltext indices visit http://dev.mysql.com/doc/refman/5.6/en/fulltext-search.html

Regarding PostgreSQL there are more ways to create a fulltext index. However, one of the easiest ways is:

ruby
ActiveRecord::Base.connection.execute "CREATE INDEX fulltext_index_books_on_title ON books USING GIN(to_tsvector('simple', title))"

Moreover, for PostgreSQL you should change the schema format in config/application.rb:

ruby
config.active_record.schema_format = :sql

Regarding compound indices for PostgreSQL, use:

ruby
ActiveRecord::Base.connection.execute "CREATE INDEX fulltext_index_books_on_title ON books USING GIN(to_tsvector('simple', author || ' ' || title))"

To handle NULL values with PostgreSQL correctly, use COALESCE both at index creation time and when specifying the search_scope:

ruby
ActiveRecord::Base.connection.execute "CREATE INDEX fulltext_index_books_on_title ON books USING GIN(to_tsvector('simple', COALESCE(author, '') || ' ' || COALESCE(title, '')))"

plus:

ruby
search_scope :search do
  attributes :title

  options :title, :type => :fulltext, coalesce: true
end

To use another PostgreSQL dictionary than simple, you have to create the index accordingly and you need tell SearchCop about it, e.g.:

ruby
search_scope :search do
  attributes :title

  options :title, :type => :fulltext, dictionary: "english"
end

For more details about PostgreSQL fulltext indices visit http://www.postgresql.org/docs/9.3/static/textsearch.html

Other indices

In case you expose non-fulltext attributes to search queries (price, stock, etc.), the respective queries, like Book.search("stock > 0"), will profit from the usual non-fulltext indices. Thus, you should add a usual index on every column you expose to search queries plus a fulltext index for every fulltext attribute.

In case you can't use fulltext indices, because you're e.g. still on MySQL 5.5 while using InnoDB or another RDBMS without fulltext support, you can make your RDBMS use usual non-fulltext indices for string columns if you don't need the left wildcard within LIKE queries. Simply supply the following option:

ruby
class User  :comments

  search_scope :search do
    attributes user: "users.username"
  end

  # ...
end

Custom table names and associations

SearchCop tries to infer a model's class name and SQL alias from the specified attributes to autodetect datatype definitions, etc. This usually works quite fine. In case you're using custom table names via self.table_name = ... or if a model is associated multiple times, SearchCop however can't infer the class and SQL alias names, e.g.

ruby
class Book  :comments
  belongs_to :user

  search_scope :search do
    attributes user: ["user.username", "users_books.username"]
  end

  # ...
end

Here, for queries to work you have to use users_books.username, because ActiveRecord assigns a different SQL alias for users within its SQL queries, because the user model is associated multiple times. However, as SearchCop now can't infer the User model from users_books, you have to add:

ruby
class Book  :users
  end

  # ...
end

to tell SearchCop about the custom SQL alias and mapping. In addition, you can always do the joins yourself via a scope {} block plus aliases and use your own custom sql aliases to become independent of names auto-assigned by ActiveRecord.

Supported operators

Query string queries support AND/and, OR/or, :, =, !=, ``, >=, NOT/not/-, (), "..." and '...'. Default operators are AND and matches, OR has precedence over AND. NOT can only be used as infix operator regarding a single attribute.

Hash based queries support and: [...] and or: [...], which take an array of not: {...}, matches: {...}, eq: {...}, not_eq: {...}, lt: {...}, lteq: {...}, gt: {...}, gteq: {...} and query: "..." arguments. Moreover, query: "..." makes it possible to create sub-queries. The other rules for query string queries apply to hash based queries as well.

Custom operators (Hash based queries)

SearchCop also provides the ability to define custom operators by defining a generator in search_scope. They can then be used with the hash based query search. This is useful when you want to use database operators that are not supported by SearchCop.

Please note, when using generators, you are responsible for sanitizing/quoting the values (see example below). Otherwise your generator will allow SQL injection. Thus, please only use generators if you know what you're doing.

For example, if you wanted to perform a LIKE query where a book title starts with a string, you can define the search scope like so:

ruby
search_scope :search do
  attributes :title

  generator :starts_with do |column_name, raw_value|
    pattern = "#{raw_value}%"
    "#{column_name} LIKE #{quote pattern}"
  end
end

When you want to perform the search you use it like this:

ruby
Book.search(title: { starts_with: "The Great" })

Security Note: The query returned from the generator will be interpolated directly into the query that goes to your database. This opens up a potential SQL Injection point in your app. If you use this feature you'll want to make sure the query you're returning is safe to execute.

Mapping

When searching in boolean, datetime, timestamp, etc. fields, SearchCop performs some mapping. The following queries are equivalent:

ruby
Book.search("available:true")
Book.search("available:1")
Book.search("available:yes")

as well as

ruby
Book.search("available:false")
Book.search("available:0")
Book.search("available:no")

For datetime and timestamp fields, SearchCop expands certain values to ranges:

ruby
Book.search("created_at:2014")
# ... WHERE created_at >= '2014-01-01 00:00:00' AND created_at = '2014-06-01 00:00:00' AND created_at = '2014-06-15 00:00:00' AND created_at  raise SearchCop::IncompatibleDatatype

Reflection

SearchCop provides reflective methods, namely #attributes, #default_attributes, #options and #aliases. You can use these methods to e.g. provide an individual search help widget for your models, that lists the attributes to search in as well as the default ones, etc.

ruby
class Product  ["products.title"], "description" => ["products.description"]}

Product.search_reflection(:search).default_attributes
# {"title" => ["products.title"]}

# ...

Semantic Versioning

Starting with version 1.0.0, SearchCop uses Semantic Versioning: SemVer

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyactiverecordfulltext-indicesfulltext-supportmysql

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库