algoliasearch-rails

repository·master·Indexed 19 days ago

https://github.com/algolia/algoliasearch-rails

A Ruby gem for integrating Algolia Search into Rails applications. It supports popular ORMs including ActiveRecord, Mongoid, and Sequel, providing tools for index schema definition, relevancy and ranking configuration, backend and frontend search implementation, and automated indexing via background jobs.

Tokens
11.2K
Snippets
50
Records
56
Agent score
60%

What's inside algoliasearch-rails

  1. Share a single index between multiple models

    master

    To share one Algolia index across different models, specify the same index_name in their algoliasearch blocks.

    Critical: You must ensure that the id (or the value returned by the id: option) is unique across all models to prevent objectID collisions. For example, prefixing the ID with the model name (e.g., "student_#{id}").

    Warning: When sharing an index, never use MyModel.reindex (the atomic version), as it will replace the entire shared index with only the records from that specific model. Always use reindex!.

    class Student < ActiveRecord::Base
      include AlgoliaSearch
      algoliasearch index_name: 'people', id: :algolia_id
    
      private
      def algolia_id
        "student_#{id}"
      end
    end
    
    class Teacher < ActiveRecord::Base
      include AlgoliaSearch
      algoliasearch index_name: 'people', id: :algolia_id
    
      private
      def algolia_id
        "teacher_#{id}"
      end
    end
  2. Run tests inside the Docker container

    master

    Once the container is running and you are inside the bash shell, you can execute tests using rspec.

    Run the entire test suite:

    bundle exec rspec

    Run a specific test file or a specific line:

    bundle exec rspec ./path/to/test_spec.rb:#line_number
    # run the whole test suite
    bundle exec rspec
    
    # run a single test
    bundle exec rspec ./path/to/test_spec.rb:#line_number
  3. Configure Backend Pagination with will_paginate or kaminari

    master

    While frontend pagination via JavaScript is recommended, you can perform pagination on the backend using will_paginate or kaminari.

    To use will_paginate, set the :pagination_backend option in your global AlgoliaSearch.configuration to :will_paginate. Once configured, calling the .search method on your model will return a paginated set compatible with your view helpers.

    AlgoliaSearch.configuration = { application_id: 'YourApplicationID', api_key: 'YourAPIKey', pagination_backend: :will_paginate }
    
    # In your controller
    @results = MyModel.search('foo', hitsPerPage: 10)
    
    # In your views
    <%= will_paginate @results %>
  4. Install Docker on OSX using Homebrew and docker-machine

    master

    For OSX users, this guide recommends using docker-machine with the virtualbox driver.

    1. Install Docker via Homebrew: brew install docker
    2. Install docker-machine: brew install docker-machine
    3. Install VirtualBox via Homebrew Cask: brew cask install virtualbox

    Note: You may need to authorize VirtualBox in System Settings > Security & Privacy.

    $ brew install docker
    $ brew install docker-machine
    $ brew cask install virtualbox
  5. Implement Frontend Search (Realtime)

    master

    For the best performance and lowest latency, it is highly recommended to use the Algolia JavaScript API Client to perform searches directly from the browser.

    To use the client provided with the gem, require it in your JavaScript manifest (e.g., application.js):

    //= require algolia/v3/algoliasearch.min
    var client = algoliasearch(ApplicationID, Search-Only-API-Key);
    var index = client.initIndex('YourIndexName');
    
    index.search('something', { hitsPerPage: 10, page: 0 })
      .then(function searchDone(content) {
        console.log(content);
      })
      .catch(function searchFailure(err) {
        console.error(err);
      });
  6. Disable indexing for testing

    master

    To prevent API calls during tests, use the disable_indexing option in the algoliasearch block. This can accept a boolean or a Proc for more complex logic.

    class User < ActiveRecord::Base
      include AlgoliaSearch
    
      # Disable indexing in test environment
      algoliasearch per_environment: true, disable_indexing: Rails.env.test? do
      end
    end
  7. Migrate search response keys from strings to symbols in v3

    master

    In algoliasearch-rails version 3, the underlying Algolia API client has changed. Response keys returned by Model.search and Model.raw_search are no longer strings; they are now always symbols. You must update your code to access results using symbol keys (e.g., :hits instead of 'hits').

    # Before v3
    results = Product.raw_search('shirt')
    p results['hits']
    
    # After v3
    results = Product.raw_search('shirt')
    p results[:hits]
  8. Configure docker-machine environment

    master

    After installing the necessary tools, create a new machine named default, set it as the default, and configure your shell environment to connect to it:

    $ docker-machine create --driver virtualbox default
    $ docker-machine env default
    $ eval "$(docker-machine env default)"
  9. Run the algolia-rails Docker container

    master

    To run the container, you must provide Algolia credentials via environment variables. The container mounts the current working directory to /app inside the container.

    Option 1: Pass variables directly in the command

    docker run -it --rm --env ALGOLIA_APP_ID=XXXXXX [...] -v $PWD:/app -w /app algolia-rails bash

    Option 2: Use exported environment variables (Recommended) Export ALGOLIA_APPLICATION_ID and ALGOLIA_API_KEY in your .bashrc or .zshrc to use Docker's shorthand syntax:

    docker run -it --rm --env ALGOLIA_APPLICATION_ID --env ALGOLIA_API_KEY -v $PWD:/app -w /app algolia-rails bash
  10. Update `Model.search_for_facet_values` usage in v3

    master

    In version 3, Model.search_for_facet_values no longer returns an array of hashes. It now returns an array of Algolia::Search::FacetHits objects. To access the value of a facet, use the .value method instead of hash bracket notation.

    # Before v3
    facets = Color.search_for_facet_values('short_name', 'bl', :query => 'black')
    puts facets.first['value']
    
    # After v3
    facets = Color.search_for_facet_values('short_name', 'bl', :query => 'black')
    facets.first.value