How do I do full-text searching in Ruby on Rails?

前端 未结 8 1952
忘了有多久
忘了有多久 2020-12-02 19:39

I would like to do full-text searching of data in my Ruby on Rails application. What options exist?

8条回答
  •  悲&欢浪女
    2020-12-02 20:13

    Two main options, depending on what you're after.

    1) Full Text Indexing and MATCH() AGAINST().

    If you're just looking to do a fast search against a few text columns in your table, you can simply use a full text index of those columns and use MATCH() AGAINST() in your queries.

    1. Create the full text index in a migration file:

       add_index :table, :column, type: :fulltext
      
    2. Query using that index:

       where( "MATCH( column ) AGAINST( ? )", term )
      

    2) ElasticSearch and Searchkick

    If you're looking for a full blown search indexing solution that allows you to search for any column in any of your records while still being lightning quick, take a look at ElasticSearch and Searchkick.

    ElasticSearch is the indexing and search engine.

    Searchkick is the integration library with Rails that makes it very easy to index your records and search them.

    Searchkick's README does a fantastic job at explaining how to get up and running and to fine tune your setup, but here is a little snippet:

    1. Install and start ElasticSearch.

       brew install elasticsearch
       brew services start elasticsearch
      
    2. Add searchkick gem to your bundle:

       bundle add searchkick --strict
      

      The --strict option just tells Bundler to use an exact version in your Gemfile, which I highly recommend.

    3. Add searchkick to a model you want to index:

       class MyModel < ApplicationRecord
         searchkick
       end
      
    4. Index your records.

       MyModel.reindex
      
    5. Search your index.

       matching_records = MyModel.search( "term" )
      

提交回复
热议问题