Esc
ZeroIndex
GuidesAPI referenceSDKsChangelogOverviewBuy ZeroIndex

Ruby

View as MarkdownThe page as plain text

The official Ruby gem, with a Rails integration that keeps your models in sync.

zeroindexv1.3.2Ruby 3.1 or later

The Ruby gem wraps the REST API in plain Ruby objects. In Rails, include one module in a model and its records are indexed every time they are saved.

Install

bundle add zeroindex
gem install zeroindex

Set up the client

require "zeroindex"

client = ZeroIndex::Client.new(
  ENV.fetch("ZEROINDEX_KEY"),
  host: "https://api.zeroindex.test"
)
products = client.index("products")

task = products.add_documents([
  { id: 1, name: "Wireless headphones", price: 129 },
  { id: 2, name: "Desk lamp", price: 59 }
])
client.wait_for_task(task.task_uid)

products.search("wirless", limit: 5).hits.each do |hit|
  puts hit["name"]
end

Rails

Include ZeroIndex::Model and list the fields to send. Saves and deletes are synced in a background job.

class Product < ApplicationRecord
  include ZeroIndex::Model

  zeroindex do
    attributes :name, :brand, :category, :price
    filterable :category, :price
  end
end

Product.search("wirless")

Errors

Failed requests raise ZeroIndex::Error with the code from the error table.

begin
  products.search("lamp", filter: "colour = red")
rescue ZeroIndex::Error => error
  warn error.message if error.code == "invalid_filter"
end