Lighthouse GraphQL RailsLighthouse GraphQL Rails
Docs
Directives
Example apps
Changelog
RubyGems
GitHub
Docs
Directives
Example apps
Changelog
RubyGems
GitHub
  • Getting Started

    • Motivation
    • Getting Started
    • Configuration
  • The Basics

    • Resolvers, Mutations and Builders
    • Generators
    • Unions, Interfaces and Scalars
    • Relay: Global Object Identification
    • Relationships
    • Filtering & Ordering
    • Mutations
    • File Uploads
    • Validation
    • Subscriptions
  • Security

    • Authentication & Authorization
    • Query Complexity & Depth
  • Performance

    • Performance at scale
    • Deferred fields: @defer and @stream
    • Caching
  • Digging Deeper

    • Schema Organisation
    • Custom Directives
    • Events
    • Testing
    • Apollo Federation
    • Best Practices
  • API Reference

    • Directives Reference

Filtering & Ordering

Lighthouse offers two complementary ways to constrain a query: simple argument filters (one directive per argument) and complex where conditions (a single structured argument the client drives dynamically). Both work on any field backed by a query — @all, @paginate, @first, @count, and the relationship directives.

Simple argument filters

Attach a filter directive to a field argument. When the client passes that argument, Lighthouse folds the corresponding clause onto the query builder. Filters compose in the order the arguments appear in the SDL.

type Query {
  users(
    status: String @eq
    role: [String!] @in
    nameSearch: String @like
    minAge: Int @where(operator: "GTE", key: "age")
  ): [User!]! @all
}
DirectiveSQL
@eqcolumn = value
@neqcolumn != value
@incolumn IN (...)
@notIncolumn NOT IN (...)
@likecolumn LIKE '%value%'
@where(operator:)operator-driven (see below)

By default the column is the snake_cased argument name (minAge → min_age). Override it with key: — above, minAge filters the age column.

@where operators

@where(operator: "...") takes these operators:

EQ, NEQ, GT, GTE, LT, LTE, IN, NIN, CONTAINS, STARTS_WITH, ENDS_WITH, IS_NULL, IS_NOT_NULL.

They are not @whereConditions' SQLOperator values, which follow PHP Lighthouse (see below).

type Query {
  events(
    after: String @where(operator: "GTE", key: "starts_at")
    titleContains: String @where(operator: "CONTAINS", key: "title")
  ): [Event!]! @all
}

Filters inside input objects

Filter directives also go on the fields of an input object. Its fields' filters apply when the client sends it, at any depth, as in PHP Lighthouse:

input PostFilter {
  title: String @like
  author: AuthorFilter
}

input AuthorFilter { id: ID @eq(key: "author_id") }

type Query {
  posts(filter: PostFilter): [Post!]! @all
}

posts(filter: { author: { id: 1 } }) keeps the posts of author 1. In a list of inputs (filters: [PostFilter!]), every input's filters apply, together. An argument with @spread filters the same way.

One filter of several: @oneOf

An input object marked @oneOf takes exactly one of its fields: to find a user by id or by email, but not both. Its fields' filters apply to the query:

input UserBy @oneOf {
  id: ID @eq
  email: String @eq
}

type Query {
  user(by: UserBy!): User @find
}
{ user(by: { email: "ada@example.com" }) { id } }

graphql-ruby validates it: a query giving two fields, none, or a null is rejected before anything resolves, and introspection reports the type's isOneOf. Every field of a @oneOf input is nullable and has no default value; the schema fails to build otherwise.

@oneOf is built in, so the SDL needn't declare it. A directive @oneOf on INPUT_OBJECT copied from elsewhere is ignored, like a definition of @skip, @include, @deprecated or @specifiedBy: graphql-ruby's own directive stays.

Ordering

@orderBy works as in PHP Lighthouse. On an argument, the client picks the order. On a field, the order is fixed.

Client-controlled ordering

Write the argument's type as _. Lighthouse then generates an input that takes the allowed columns as an enum, together with the SortOrder enum:

type Query {
  posts(orderBy: _ @orderBy(columns: ["posted_at", "title"])): [Post!]! @all
}

Lighthouse generates this from it:

"Order by clause for Query.posts.orderBy."
input QueryPostsOrderByOrderByClause {
  "The column that is used for ordering."
  column: QueryPostsOrderByColumn!

  "The direction that is used for ordering."
  order: SortOrder!
}

"Allowed column names for Query.posts.orderBy."
enum QueryPostsOrderByColumn {
  POSTED_AT @enum(value: "posted_at")
  TITLE @enum(value: "title")
}

"Directions for ordering a list of records."
enum SortOrder {
  ASC
  DESC
}

The argument becomes orderBy: [QueryPostsOrderByOrderByClause!]. The client passes a list of clauses, which apply in turn:

{
  posts(orderBy: [{ column: POSTED_AT, order: DESC }, { column: TITLE, order: ASC }]) {
    title
  }
}

The names follow <Type><Field><Argument>: QueryPostsOrderBy… for Query.posts(orderBy:). Each clause needs an order. Without columns:, columnsEnum: or relations:, the argument takes the shared OrderByClause, whose column is a String!. That allows any column, so restrict the columns whenever clients are not trusted.

To reuse one enum on several fields, name it with columnsEnum:. Its @enum(value:) gives each value's column:

type Query {
  allPosts(orderBy: _ @orderBy(columnsEnum: "PostColumn")): [Post!]! @all
  paginatedPosts(orderBy: _ @orderBy(columnsEnum: "PostColumn")): [Post!]! @paginate
}

enum PostColumn {
  POSTED_AT @enum(value: "posted_at")
  TITLE @enum(value: "title")
}

columns: and columnsEnum: cannot be used together.

Ordering by a relation

relations: lets the client order by an aggregate of a relation. Without columns, that aggregate is COUNT. With a relation's own columns: (or columnsEnum:), it is AVG, MIN, MAX, SUM or COUNT of one of them:

type Query {
  users(
    orderBy: _ @orderBy(columns: ["name"], relations: [{ relation: "posts" }, { relation: "tasks", columns: ["difficulty"] }])
  ): [User!]! @all
}
{
  users(
    orderBy: [
      { posts: { aggregate: COUNT }, order: DESC }
      { tasks: { aggregate: MAX, column: DIFFICULTY }, order: DESC }
      { column: NAME, order: ASC }
    ]
  ) {
    name
  }
}

The argument then takes [QueryUsersOrderByRelationOrderByClause!]. Each clause names exactly one of column and the relations. Each relation has an input of its own, QueryUsersOrderByPosts / QueryUsersOrderByTasks, with the OrderByRelationAggregateFunction or OrderByRelationWithColumnAggregateFunction enum.

The aggregate is computed once per record, in a LEFT JOIN on a grouped subquery. A record with no related records is still listed, with a COUNT of 0. This also works on a relationship field (posts(orderBy: _ @orderBy(...)): [Post!]! @hasMany), including when its pages are batched.

Predefined ordering

On a field, @orderBy(column:, direction:) always orders the result, whatever the client sends:

type Query {
  latestUsers: [User!]! @all @orderBy(column: "created_at", direction: DESC)
}

A field's @orderBy applies after the client's orderBy argument, so on a field with both, it breaks ties:

type Query {
  posts(orderBy: _ @orderBy(columns: ["title"])): [Post!]! @paginate @orderBy(column: "created_at", direction: DESC)
}

An argument written with a type of its own, such as orderBy: [MyClause!] @orderBy, keeps that type. Its input needs a column and an order.

Full-text search

@search runs a field's query through a full-text engine when the client sends a search term, as PHP Lighthouse's does through Laravel Scout (the directive is in directives.md). Ruby has no Scout: Lighthouse supports the two gems Rails apps use, behind one adapter seam. Neither is a dependency of Lighthouse, so add the one you use to your Gemfile.

type Query {
  posts(
    search: String @search
    authorId: ID @eq(key: "author_id")
    orderBy: _ @orderBy(columns: ["created_at"])
  ): [Post!]! @paginate
}

The search runs when the client sends a string for the argument ("" too). null or nothing leaves the query to the database.

pg_searchSearchkick
SearchesPostgreSQL's full-text search, in the tablean Elasticsearch or OpenSearch index, a copy of the table
The search isa scope on the field's relationan engine request that answers records
Everything else Lighthouse appliescomposes on it@eq, @trashed, @builder on an argument, and the model's search_where
Fieldsany that applies a search@all, @paginate of the model's whole table, @find, @first, a resolver of your own
Up to datealwaysonce the index is (callbacks, jobs)

Lighthouse is tested with Searchkick 6.2 on Elasticsearch 9.5 and on OpenSearch 2.19 and 3.9, and with pg_search 2.3 and 2.4 on PostgreSQL 16 (the example app's suite).

Setting up pg_search

# Gemfile
gem 'pg_search'
class Post < ApplicationRecord
  include PgSearch::Model

  pg_search_scope :search, against: { title: 'A', body: 'B' }, using: { tsearch: { prefix: true } }
  pg_search_scope :search_title, against: :title
end

@search calls the scope search, or the one within: names: @search(within: "search_title"). There is nothing to index: the scope searches the table, so a search sees every change at once. On a model that uses both gems, a within: that names one of its pg_search scopes searches with pg_search; no within:, or any other, searches with Searchkick (where it names an index).

Setting up Searchkick

# Gemfile
gem 'searchkick'
gem 'elasticsearch'      # Elasticsearch: the client's major version is the server's (9 for Elasticsearch 9, 8 for 8)
# or
gem 'opensearch-ruby'    # OpenSearch 2 or 3

Searchkick talks to ELASTICSEARCH_URL or OPENSEARCH_URL (http://localhost:9200 by default). With both clients loaded (say, Elasticsearch in production and OpenSearch elsewhere), Searchkick refuses to guess: name the one in use in an initializer, and require only it:

# config/initializers/searchkick.rb, with both gems `require: false` in the Gemfile
if ENV['OPENSEARCH_URL']
  require 'opensearch'
  Searchkick.client_type = :opensearch
else
  require 'elasticsearch'
  Searchkick.client_type = :elasticsearch
end

Then the model. The index is a copy of what search_data says, so it must hold the text to search and every column a filter of the field reads: the key: of each @eq, the soft-delete column for @trashed, and those search_where filters on. An @eq on a column the index does not hold matches nothing.

class Comment < ApplicationRecord
  belongs_to :post

  searchkick callbacks: :async

  # What the index holds: `body` to search, `post_id` for an `@eq(key: "post_id")` argument,
  # and whether the post is published, for search_where.
  def search_data = { body: body, post_id: post_id, published: post.published? }

  # Which records are indexed at all: what must not be found must not be indexed.
  def should_index? = post.published?

  # What a reindex loads with each batch, for search_data and should_index?.
  scope :search_import, -> { includes(:post) }

  # What a search may return, checked in the database as the records it finds load.
  scope :search_results, -> { where(post: Post.published) }

  # The same, in the engine, so that totals and pages count only those.
  def self.search_where = { published: true }
end
type Query {
  searchComments(search: String! @search, postId: ID @eq(key: "post_id")): [Comment!]! @paginate
}

Run Comment.reindex once, to create the index and fill it, and again after you change search_data or the index's settings. Searchkick's callbacks keep it up to date as records change: in the same request by default, or in an Active Job with callbacks: :async (start a worker, such as bin/jobs for Solid Queue). should_index? only decides on the record that changed: when another record decides it (unpublishing a post hides its comments), reindex those too: the example app's Post calls comments.reindex(mode: :async) in an after_commit when published changes. search_import is Searchkick's: without it, a should_index? or search_data that reads an association loads it once per record.

What Lighthouse does with pg_search

@search calls the scope on the field's relation. Because a pg_search scope is a relation, everything else Lighthouse does composes on it: the field's scopes:, @builder, @whereAuth, every argument filter, @whereConditions, @orderBy, nested fields and nested @paginate (batched through one window query), @count, @first, @find and @canQuery.

A mass mutation (@delete, @forceDelete, @restore) can take a @search argument too: it acts on the records the search finds. It still refuses to run without a filter (Would modify all models, use an argument to filter.), and a @search argument counts as one only when the search runs, for a string: deletePosts(search: null) deletes nothing, as in PHP Lighthouse. With Searchkick a mass mutation is a schema error.

Order. A search is in order of relevance: pg_search's rank always sorts first. The orders the relation already had break its ties, in the order they apply, as on a field without a search: the model's default scope, the field's scopes:, the model's search_results scope; then the client's orderBy, the field's @orderBy(column:), and the primary key ends the order, once, unless an order before already names it. A client that sorts by date gets the best matches first and, among equally ranked ones, the newest; matches that rank and sort alike come back in the same order every time, on every field. pg_search's own tie-break, the primary key, is dropped so that these orders decide (a node of its own in pg_search 2.4, the end of the rank's SQL in 2.3); an order_within_rank: the scope names is kept, right after the rank.

What Lighthouse does with Searchkick

Searchkick queries Elasticsearch or OpenSearch, which knows nothing of your database, so what narrows a search is translated into the engine's filters. Lighthouse does it for the directives of PHP Lighthouse's ScoutBuilderDirective:

DirectiveIn the search
@eqwhere: { column => value }, a filter on the indexed column
@trasheda filter on the indexed soft-delete column: below
@builder on an argumentgets the Lighthouse::Search::Query instead of the relation (below)

They work at any depth of input objects (filter: CommentFilter with @eq fields). The engine answers with Active Record records, in relevance order, loaded in one query through the model (and its default scope), so nested fields and the Dataloader work on them as usual.

# app/graphql/builders/title_fields.rb: `titleOnly: Boolean @builder(class: "TitleFields")`
class Builders::TitleFields
  def self.call(target, value, _context)
    return target unless value
    return target.where(body: nil) unless target.is_a?(Lighthouse::Search::Query)  # a relation

    target.options[:fields] = ['title^10']  # passed to Searchkick's search
    target
  end
end

A query holds model, term, index, wheres (the [column, value] pairs of @eq, in order), trashed and options: the options of Searchkick's search that rank, highlight or aggregate the hits, Lighthouse::Search::Searchkick::Options::BUILDER_OPTIONS: fields:, match:, operator:, where:, order:, boost_by:, boost_where:, boost_by_distance:, boost_by_recency:, indices_boost:, misspellings:, highlight:, aggs:, smart_aggs:, emoji:, exclude:, conversions:, conversions_term:, explain:, debug:, includes:, model_includes:, scope_results:, body_options: (min_score, explain, profile, timeout) and timeout:. Any other, one that decides what loads, how it pages or what it counts (load:, index_name:, models:, unscope:, select:, page:, body:, body_options: { query: ... }, track_total_hits, ...), is an error the client reads, reported to Config.on_error: Lighthouse sets those. Lighthouse adds where:, with yours, the model's search_where, every @eq and @trashed all holding: keys are read alike, symbols or strings, and conditions on one column (yours and an @eq's, or two @eq of a list of inputs) are ANDed (_and), never overwritten. It adds index_name: (from within:), load: true, track_total_hits: true to your body_options: and its own scope_results:, which runs after yours, so yours cannot widen what loads.

Which fields. Whatever the engine, something must apply the search: a directive that runs the field's argument filters (@all, @paginate, @find, @first, @count, @aggregate, a relationship, a mass mutation), or your own code, which reads it through resolve_info.enhance_builder: @field, the conventional class of a root field, or a method of the type's class. A field nothing resolves but graphql-ruby's default reader, which reads it off the parent (type User { comments(search: String @search): [Comment!]! }), or one whose directive runs no filters (@create, @method, ...), would ignore the search: it is a schema error, nothing applies the search. Each resolver class says what it does, through Contracts::FieldResolver, which by default says it applies no search: a directive of your own opts in with def self.applies_search? = true (it runs the field's filters, apply_where_filters or resolve_info.enhance_builder), and def self.takes_search_results?(type, field_def, directive, root_kind) = true when it also takes a Searchkick Lighthouse::Search::Result.

The engine answers with records, not a relation, so @search with Searchkick is for @all, @paginate of the model's whole table (on a root field, with its own model:, or where the parent type's model has no association of the field's name; a parent type that is no model is refused, as only a query's records would tell what it pages, and a record that turns out to page an association answers a client error), @first, @find and your own code. @first answers the best match that loads; @find the one match, or null, and an error when the engine counts more than one, as PHP Lighthouse's @find on Scout's get(). An id argument of @find without a filter directive selects by primary key in the database, which the engine cannot: give it @eq, which the engine applies, or the field is a schema error. Any other field (@count, @aggregate, a mass mutation, a nested relationship) is a schema error at build, when Lighthouse can tell the field's model: PHP Lighthouse ignores the search on @count and @aggregate (they drop the Scout builder enhanceBuilder returns, and count every record) and fails on a mass mutation, which takes only a query builder. For the same reason a field with scopes:, @builder, @whereAuth or @orderBy(column:), or an @canQuery with scopes:, is a schema error: PHP Lighthouse drops those silently when it searches, and a search that skipped @whereAuth would return records the user must not see. Lighthouse fails when the schema is built instead. Put the constraint in the index (search_data and an @eq argument), in the model's search_results scope, or search with pg_search.

At run time, a client that sends an argument whose directive the engine cannot apply (@neq, @in, @like, @orderBy, @whereConditions, ...) with a search, or two @search arguments, gets an error, as in PHP Lighthouse. Such an argument with a default value would be sent on every search, as graphql-ruby fills the default in (and PHP Lighthouse fails every search of the field): it is a schema error. So is an input field that holds a value the client did not send, as graphql-ruby fills it in: the value an argument's default object gives it, else its own default, inside a default object or an input object the client must send (filter: PostFilter!). An input field's default under a parent the client may leave out (filter: PostFilter) applies only when it sends the parent, and is not refused: a search with that parent is then the run-time error above. A default for @eq, @trashed or @builder is fine.

A directive that does not change the query is taken with a search: @limit cuts what the field resolved (not @limit(builder: true), a LIMIT on the query, which is refused); an argument directive of your own says so with def self.changes_query?(directive_node) = false. (@in, @notIn and @whereKey are refused with a search, as in PHP Lighthouse, where only @eq, @trashed and @builder write to Scout's builder.)

Order. The engine's relevance; ties as the engine breaks them. @orderBy is refused with a search; an @builder on an argument can set Searchkick's order:.

Pagination and totals

@paginate pages a search with all three types: PAGINATOR, SIMPLE and CONNECTION, whose cursors are positions. With pg_search it pages the relation, as any other. With Searchkick each page is one engine request (offset: and limit:), whose response holds the total too, so a page and paginatorInfo { total } cost one request. Unlike Scout, first: 0 can still count.

Pages follow the engine's positions. A hit may not load (the model's default scope or search_results scope drops it, or its row is gone from the database): the page then holds fewer records than first, but its positions are still the engine's. firstItem and lastItem are the positions of its first and last record; SIMPLE's hasMorePages says whether the engine has hits past the page; and a CONNECTION's cursors are the records' engine positions, its startCursor and endCursor its first and last edge's, as Relay's (a page whose hits all failed to load has no edge, and its endCursor is past them, so the client walks on). No record shows twice, and none is skipped.

The total is exact. Elasticsearch and OpenSearch stop counting matches at 10,000 unless asked (track_total_hits), which made total, lastPage and hasMorePages wrong past it. Lighthouse asks on every search, and nothing turns it off: totals, the pages within the result window and @canQuery's check of every hit (below) rely on every match being counted, and an estimate (track_total_hits: false, or a number, which stops at it) would let a page serve a record no check saw. An @builder whose body_options set track_total_hits is an error the client reads, reported to Config.on_error, as is a response whose total is not exact.

Reads by @all. @all reads what the client asks for: first records, as many as an argument's @limit (without builder: true) lets the field answer, or every match. One request reads 10,000 records at most, and no further than the result window. When that answers fewer than asked while more match, the field answers those records with an error next to them: @all answered 10000 of the 12345 matches the search finds from offset 0: a search reads 10000 at most at once, and no further than its first 10000 matches (the index.max_result_window). Use @paginate, or first and offset, to read the others.

The result window. The engines page through the first 10,000 matches only (the index's index.max_result_window). Lighthouse reads no further: a page that runs past it is cut at its end, and a page that starts past it is an error the client reads:

The search reads no further than its first 10000 matches (the index.max_result_window of Comment), so offset 10000 is past them. Narrow the search instead.

total stays the true number of matches; lastPage, hasMorePages and hasNextPage count only the pages within the window, so no page is announced that would then be refused.

Lighthouse reads the window from the engine: the index.max_result_window of the index the search reads (the model's, or the one within: names; the smallest of an alias's indices), 10,000 when it sets none. It is read once a minute per index at most, as the mapping is (below). When the settings cannot be read, it takes the window the model sets for its own index, searchkick max_result_window: 50_000 (or settings: { index: { max_result_window: 50_000 } }, with symbol or string keys, nested or as 'index.max_result_window'), a billion with searchkick deep_paging: true, else 10,000, for any index. No request asks past it. If the engine still refuses a page as past its window (it changed within the minute), the refusal becomes the same error, without the number: The search reads no further than the index.max_result_window of Comment. Narrow the search instead. Raising the window lets clients page deeper at the engine's expense; Searchkick advises against it.

Soft deletes in a search

With pg_search, @trashed and @softDeletes filter the relation, as without a search.

With Searchkick, @trashed filters on the soft-delete column the index holds, so search_data must hold it (deleted_at: deleted_at), or ONLY and WITHOUT are an error (WITH filters nothing): Comment's index does not hold deleted_at, which @trashed filters the search on: add it to search_data. Lighthouse reads the columns from search_data on a blank record, for the model's own index; for another index within: names, or when search_data raises (it reads an association), from that index's mapping on the engine. Reading the mapping needs the view_index_metadata privilege on the index (the settings, for the result window, too). It is read at most once a minute per model and index, by one thread while the others wait for it (a reindex may add or remove a column); a read that fails is reported to Config.on_error and tried again after five seconds, however many requests ask. When neither can be read, ONLY and WITHOUT are refused, rather than filter on a column the index may not hold, with the engine's reason: @trashed cannot tell whether Comment's index holds deleted_at ... (Elastic::Transport::Transport::Errors::Forbidden: ...; reading it needs the view_index_metadata privilege on the index). The filter Lighthouse adds on its own (below) goes on: it holds either way. (A column every document leaves null has no mapping yet: let search_data run on a blank record.) The column is the one the database path filters on (Config.soft_deletes): paranoia's (paranoia_column, and its sentinel_value in place of null for the records that are not trashed), discard's (discard_column), a Column.new(:archived_at)'s, else deleted_at. An adapter of your own tells it with column(model) and kept_value(model). Config.soft_deletes is the one place to name it: the support check, the engine's filter and the records' load all read it, as the database filters do.

trashed:In the engineLoads the records
ONLYa value in the column, other than paranoia's sentinelthe trashed ones, past the default scope that hides them
WITHno filterpast that default scope
WITHOUTno value in the column, or the sentinelthe ones not trashed
omittedas WITHOUT when the model's default scope hides trashed records, else no filterthrough the model

The soft-delete column is Lighthouse's to filter on: a model whose default scope hides trashed records (paranoia's, discard's kept when the model adds it, or your own on the column) is filtered on it in the engine as WITHOUT when the client does not say, so its index must hold the column too. Its search_where (below) leaves the column out, {} when nothing else narrows: a search_where that names it anywhere (in _and, _or, _not too) is an error the client reads at the first search, reported to Config.on_error, as its condition could not give way to @trashed. Lighthouse loads the records with Support::SoftDeletes.filter, the database's @trashed, through Searchkick's scope_results:, as Scout loads them withTrashed(), so a record trashed or restored since the index read it is not answered for the wrong trashed:. All of this needs trashed records in the index: a model that leaves them out (should_index? returning false once trashed) finds none with ONLY.

What a search counts

A search counts only what it can load: its total, lastPage and pages are the engine's, and the engine knows nothing of the database. What narrows the records a search loads must narrow the engine's hits the same way, or a total would count what the client cannot see: with default_scope { where(tenant_id: Current.tenant_id) }, one tenant's search would load its own records but count every tenant's matches. So a Searchkick model with a default scope, a search_results scope (below), or an STI subclass that searches its parent's index without searchkick inheritance: true (which filters the engine by type), must define search_where. Any default scope counts, as declared: what one selects may depend on the request (where(tenant_id: Current.tenant_id) if Current.tenant_id narrows nothing when the schema is built, outside one), so Lighthouse does not judge it by what it selects. search_where is the engine's where: for the same records, from what search_data indexes ({} for a default scope that only orders, or only hides trashed records, which Lighthouse filters on itself: above). Every search of the model ANDs it in. Without it the model is a schema error (or, for a field whose model Lighthouse cannot tell, an error at the first search):

class Post < ApplicationRecord
  searchkick
  default_scope { where(tenant_id: Current.tenant_id) }

  def search_data = { title: title, tenant_id: tenant_id }
  def self.search_where = { tenant_id: Current.tenant_id }
end

search_where returns {} when the index holds no record the scopes would leave out (should_index? keeps them out). The scopes still apply as the hits load, a guard for an index not yet updated: a record the index holds after it should have left is never returned, and until the index is updated, the total counts it. That holds for a model that loads searchkick unscope: true too, which Searchkick loads through unscoped: Lighthouse merges the model's default scope back in. So do the filters the engine applied that the database can apply too: @trashed's, and each @eq (or query.where) on a column of the model whose value the database compares as the engine does, a scalar, a list or a Range of them; a record the index still holds as it was (its author changed since) is not answered for a filter it no longer matches. A condition only the index holds (a field search_data computes, an engine operator such as { gt: 3 }, a Regexp) is the index's alone. That window, the time a reindex job takes, is the only one where a count includes a record the client cannot load; filter on an indexed column in search_where to keep counts exact even then, for what the index itself says.

Keeping private records out of a search

A search answers from the index, not the table. What must not be found must not be indexed: should_index? decides it per record, and the index follows as callbacks or jobs run. Until they do, or for good if a job fails, the index still holds a record that must no longer be found.

A model's search_results scope, when it has one, is what a search of it may return, checked in the database. Lighthouse loads the records Searchkick finds through it (Searchkick's scope_results:), so a record the index still holds is not returned; a page may come out short (its positions are still the engine's), and Searchkick logs it as a record the database does not have ("Records in search index do not exist in database"). With Searchkick it needs its engine counterpart, search_where (above), so that totals count the same records. With pg_search the scope narrows the search itself, totals included.

scope :search_results, -> { where(post: Post.published) }
def self.search_where = { published: true } # search_data indexes `published: post.published?`

It is the model's, the same for every client: what depends on the user belongs in @canQuery or @canResolved, or, with pg_search, in @whereAuth.

@canQuery on a searched field

@canQuery checks the policy against each record the field's query would return. When the client searches, those are the records the search finds: all of them, not only the page the field returns, as PHP Lighthouse checks the hits of the Scout builder. With Searchkick that is one engine request, of 10,000 records at most, each loaded and checked, whose hits then serve the field's page: what the index gains between the check and the page is never answered unchecked. They serve that one resolution of the field only, handed from @canQuery to the field's resolver, never kept in the query's context: each field, each place of it in the response, each query of a multiplex and each run of a stored subscription context searches again. A search that finds more within the result window (a page cannot reach past it) is an error, @canQuery checks every record the search finds, at most 10000, and this one finds 12345. Narrow the search., passed to the client or replaced as action: says, as any failed check. With pg_search, the scope's records, all of them. Its model: must be searchable, and with Searchkick its scopes: are a schema error (PHP Lighthouse drops them). @canResolved checks only the records the field returns, after it resolves.

In a resolver of your own

resolve_info.enhance_builder(Comment.all) applies the field's search too (see resolvers.md). With pg_search it answers the relation, searched; with Searchkick, when the client searched, a Lighthouse::Search::Result, as PHP Lighthouse answers Scout's builder: records(first:, offset:) reads the records, count the total. The engine searches the model's whole index, so the relation must select what the model's own does: Comment.all, Comment itself, or either in another order. Any other (Comment.where(...), Comment.unscoped.where(...), a with_deleted, a rewhere, a merge, joins, none) is refused with a Lighthouse::DefinitionError, since the engine would drop its conditions and could return records it leaves out. The check compares every condition, with its values, to the model's own, and refuses when in doubt: a model whose default scope reads the clock (where('published_at <= ?', Time.current)) cannot be told from another, and is refused there. @all, @paginate and @canQuery, which build the model's relation themselves, need no such check.

type Query {
  found(search: String @search, postId: ID @eq(key: "post_id")): [Comment!]! @field(resolver: "Found")
}
class Found
  def self.call(_object, _args, _context, resolve_info)
    found = resolve_info.enhance_builder(Comment.all)
    found.is_a?(Lighthouse::Search::Result) ? found.records(first: 20) : found.limit(20)
  end
end

Searching several models together

A field of a union or an interface searches the models of its types together, in one search: a global search box that finds posts and users at once, the best matches of both first. PHP Lighthouse has no such search (Scout searches one model).

union SearchResult = Post | User

type Query {
  everything(search: String! @search): [SearchResult!]! @paginate
}
{
  everything(search: "rails", first: 10) {
    data { __typename ... on Post { title } ... on User { name } }
    paginatorInfo { total }
  }
}

The models are those of the union's types, or of the object types that implement the interface: each type is a model's (@model(class:), or its name). Each record answers as its model's type. One search over all of them answers one ranked list, paged as any search (@all, @paginate of any type), with an exact total.

  • Searchkick searches the models' indices in one request (Searchkick.search(models: [...])). What narrows a model holds in its own index only, through the engine's _index (which Elasticsearch and OpenSearch match against the alias Searchkick names): its search_where, and the records its default scope hides. Each model's hits load through its own default scope, search_results scope and the conditions the database applies alike, as for a search of it alone, so a model with a default scope or search_results still needs search_where.

  • pg_search searches its multisearch documents (pg_search_documents), which each multisearchable model keeps, ranked together by PgSearch.multisearch_options. A document counts only when its record is one its model's relation selects (its default scope, its search_results scope, the field's @eq), narrowed in the database, so a page and its total hold only what loads, whatever documents are left behind (a record deleted without its callbacks).

    class Post < ApplicationRecord
      include PgSearch::Model
      multisearchable against: %i[title body], if: :published?
    end
    
    class User < ApplicationRecord
      include PgSearch::Model
      multisearchable against: :name
    end
    
    # config/initializers/pg_search.rb
    PgSearch.multisearch_options = { using: { tsearch: { prefix: true } } }
    

The field's other arguments narrow every model alike: @eq holds in each index (or each model's relation), and matches nothing in one that does not have the column. @builder on an argument writes to the search as for one model (with pg_search, it may not set Searchkick's options). @canQuery checks each record the search finds by its own policy.

The schema is refused when it is built, as nothing applies would be, where such a field:

  • is not a root field with @all or @paginate (a model: on the directive searches that one model, as any field);
  • has no search to run: there is no table to list without one, so it takes one @search, on a top-level, non-null argument (search: String!), with no within:, which names one model's index or scope;
  • has a type that is no model's, or models no one engine searches together (a Searchkick model and a pg_search one; a pg_search model that is not multisearchable), or a model the engine cannot search as it is (Searchkick's search_where, above);
  • asks for what one model's search would apply, and a search of several cannot: scopes:, @builder, @whereAuth or @orderBy(column:) on the field, @trashed (each model has its own soft deletes), scopes: on @canQuery, or a default value for a directive the engine cannot apply.

An adapter of your own searches models together when it answers searchable_together?(model), together_error(model) (why the model cannot be searched with others as it is, or nil) and page for a Lighthouse::Search::Query that has models (and no model); query.for(model) is the same search of one of them.

Choosing the engine

By default the engine is detected per model: Searchkick if it calls searchkick, else pg_search if it includes PgSearch::Model. Config.search replaces that with one adapter (Lighthouse::Search::PgSearch.new, Lighthouse::Search::Searchkick.new) or your own. An adapter answers searchable?(model, index), relational? and either scope(relation, query) (a relational one, like pg_search) or page(query, offset:, limit:) returning [entries, total], one entry per engine hit (the record, or nil for one it could not load) and the total, every match counted (an Integer: anything else is an error the client reads), and optionally result_window(query) (10,000 when it does not, nil when it cannot tell), named?(model, index) (does within: name something of its own on the model: picked first when it does) and model_error(model) (why a model cannot be searched as it is: a schema error). This protocol is experimental.

Errors

CasePHP LighthouseLighthouse
Two @search arguments sentScoutException at run timeclient error
An argument the engine cannot apply is sentScoutException at run timesame with Searchkick; none with pg_search
Model not searchableScoutException at run timeschema error at build, once the field's model is known
within: not a stringDefinitionExceptionschema error at build
Nested field (a relation)ScoutException at run timeschema error with Searchkick; works with pg_search
@find when the search finds more than one record"The query returned more than one result."same, counted by the engine with Searchkick
@find with an id argument without a filter directivenot a case: PHP's @find selects by its arguments' directives onlyschema error with Searchkick (give it @eq); works with pg_search
@count, @aggregatethe search ignored: every record countedschema error with Searchkick; works with pg_search
A mass mutation (@delete, @restore, @forceDelete)a type error at run timeschema error with Searchkick; works with pg_search
Field has scopes:, @builder, @whereAuth, @orderBy(column:)dropped silentlyschema error with Searchkick (a client error, reported, for a resolver of your own whose type is no model); applied with pg_search
@canQuery with scopes:dropped silentlyschema error with Searchkick; applied with pg_search
A default value for a directive the engine cannot applyScoutException on every searchschema error with Searchkick; applied with pg_search
A mass mutation's @search sent as nullnot a filter: "Would modify all models"same
@trashed ONLY / WITHOUT on an index that does not hold the column, or whose columns cannot be toldnot a case: Scout indexes its own __soft_deleted (with scout.soft_delete on)client error
A page past the result windowdepends on the Scout driverclient error
@canQuery on more than 10,000 matches a page can reachchecks the hits Scout's get() returnsclient error
enhance_builder given a narrowed relationconditions droppedclient error, reported to Config.on_error
A @search nothing applies (the default reader, @create, ...)ignoredschema error
A directive of your own on a searched field, which does not say it applies a search(no such contract)schema error
A Searchkick model with a default scope or search_results, without search_wherethe engine counts what does not loadschema error
A nested @paginate whose record pages an association its type's model lacksScoutException at run timeclient error
A filter raises (on any field)the errorthe error, reported to Config.on_error, for the schema's rescue_from
The engine raises, as the field resolves or as a page asks for itthe errorthe same
A search the field's own directives would narrow, on a field whose model the build could not telldirectives dropped silentlyclient error, reported
@all answers fewer than asked while more match (10,000 at once, the result window)Scout's get() answers its driver's defaultthose records, with an error next to them
body_options setting track_total_hits, or a total the engine did not count to the endan estimateclient error, reported
A search_where naming the soft-delete column(no such hook)client error, reported
An @builder setting a Searchkick option that decides what loads, pages or counts (load: false, ...)appliedclient error, reported
An STI subclass searching its parent's index without inheritance: true nor search_wherecounts the other typesschema error

Complex where conditions

@whereConditions works as in PHP Lighthouse. The client builds the WHERE clause itself, from conditions joined by AND and OR, and from HAS checks on relations. Write the argument's type as _, and declare the allowed columns:

type Query {
  people(
    where: _ @whereConditions(columns: ["age", "type", "haircolour", "height"])
  ): [Person!]! @all
}

Lighthouse generates these types for Query.people(where:):

"Dynamic WHERE conditions for the `where` argument of Query.people."
input QueryPeopleWhereWhereConditions {
  column: QueryPeopleWhereColumn
  operator: SQLOperator = EQ
  value: Mixed
  AND: [QueryPeopleWhereWhereConditions!]
  OR: [QueryPeopleWhereWhereConditions!]
  HAS: QueryPeopleWhereWhereConditionsRelation
}

"Allowed column names for Query.people.where."
enum QueryPeopleWhereColumn {
  AGE @enum(value: "age")
  TYPE @enum(value: "type")
  HAIRCOLOUR @enum(value: "haircolour")
  HEIGHT @enum(value: "height")
}

input QueryPeopleWhereWhereConditionsRelation {
  relation: String!
  operator: SQLOperator = GTE
  amount: Int = 1
  condition: QueryPeopleWhereWhereConditionsHasCondition
}

QueryPeopleWhereWhereConditionsHasCondition has the same fields as the conditions input, but its column is a String. It filters the related records, whose columns are not the model's.

The conditions of one level all hold. An AND list is a group whose conditions all hold, and an OR list is a group where at least one does:

{
  people(
    where: {
      AND: [
        { column: AGE, operator: GT, value: 37 }
        { column: TYPE, value: "Actor" }
        {
          OR: [
            { column: HAIRCOLOUR, value: "red" }
            { column: HEIGHT, operator: GTE, value: 150 }
          ]
        }
      ]
    }
  ) {
    name
  }
}
{
  people(
    where: {
      AND: [
        { column: HAIRCOLOUR, operator: IS_NULL }
        { column: HEIGHT, operator: BETWEEN, value: [150, 200] }
      ]
    }
  ) {
    name
  }
}

where: null filters nothing.

Operators

The generated SQLOperator enum has PHP Lighthouse's operators. IS_NULL and IS_NOT_NULL take no value. Any other operator needs one, or the query fails with "Did not receive a value to match the WhereConditions for column …".

OperatorSQLvalue
EQ (default)=a scalar
NEQ!=a scalar
GT, GTE, LT, LTE>, >=, <, <=a scalar
LIKE, NOT_LIKELIKE, NOT LIKEa pattern: "%Rails%"
IN, NOT_ININ, NOT INa list
BETWEEN, NOT_BETWEENBETWEEN, NOT BETWEEN[from, to]
IS_NULL, IS_NOT_NULLIS NULL, IS NOT NULLnone

Related records — HAS

HAS keeps the records that have related records. By default, at least one, which is operator: GTE, amount: 1. Its condition filters the related records, on their own table's columns:

{
  users(where: { HAS: { relation: "posts", amount: 3, condition: { column: "published", value: true } } }) {
    name
  }
}

relation names an association of the model (posts, or blogPosts for blog_posts). { relation: "posts", operator: LT, amount: 1 } keeps the users with no posts. A condition can hold its own HAS, which checks the related records' relations.

Without columns:

Without columns: or columnsEnum:, the argument takes the shared WhereConditions input, whose column is a String. A column a client names there must be an identifier or table.column, optionally followed by a JSON path (meta->tags). Anything else fails with "Column names may contain only alphanumerics or underscores, optionally a table and a JSON path (posts.meta->tags), and may not begin with a digit, got: …". Any column of the table can still be filtered on, so declare the allowed columns when clients are not trusted.

JSON columns

As in PHP Lighthouse (and Laravel), a column can point into a JSON document with ->: meta->series, meta->author->name, and meta->tags->0 for an array element. @whereConditions, @whereHasConditions and @orderBy, on an argument or on a field, take it in columns: like any column:

type Query {
  posts(
    where: _ @whereConditions(columns: ["title", "meta->series", "meta->rank"])
    orderBy: _ @orderBy(columns: ["meta->rank"])
  ): [Post!]! @all
  rankedPosts: [Post!]! @all @orderBy(column: "meta->rank", direction: DESC)
}

The generated enum names the path with __ (META__SERIES, META__AUTHOR__NAME):

{
  posts(
    where: { AND: [{ column: META__SERIES, value: "graphql" }, { column: META__RANK, operator: GT, value: 9 }] }
    orderBy: [{ column: META__RANK, order: DESC }]
  ) {
    title
  }
}

The value at the path is compiled for the database: "meta"->>'series' on PostgreSQL, JSON_UNQUOTE(JSON_EXTRACT(meta, '$."series"')) on MySQL, and json_extract(meta, '$."series"') on SQLite. Unlike Laravel, it behaves the same on all three:

  • A number compares as a number (meta->rank GT 9 keeps 10), and a boolean as a boolean. LIKE compares the text.
  • IS_NULL holds for a missing key and for a JSON null.
  • @orderBy orders by the JSON value, so numbers sort numerically.

A custom handler

handler: names a class, looked up in Config.namespaces[:builders] (Builders::). It applies the conditions instead of Lighthouse:

type Query {
  people(where: _ @whereConditions(columns: ["age"], handler: "PeopleConditions")): [Person!]! @all
}
class Builders::PeopleConditions
  # `conditions` as the client sent them: { column: "age", operator: "GT", value: 37, and: [...], ... }
  def self.call(relation, conditions)
    relation.where(...)
  end
end

Use "Class@method" to call another method.

@whereHasConditions

@whereHasConditions keeps the records that have at least one related record matching the client's conditions. The input is the same as @whereConditions', applied to the relation:

type Query {
  people(hasRole: _ @whereHasConditions(columns: ["name", "access_level"])): [Person!]! @all
}
{
  people(hasRole: { column: ACCESS_LEVEL, operator: GTE, value: 5 }) {
    name
  }
}

The relation is the argument's name without has (hasRole → role, and roles if the model has that instead). You can also name it with relation:: work: _ @whereHasConditions(relation: "tasks"). The generated input is QueryPeopleHasRoleWhereHasConditions.

hasRole: {} keeps the people with any role. hasRole: null filters nothing.

The client's conditions are an argument directive like any other, so they also work on @paginate, @count, @first, the relationship directives, and resolve_info.enhance_builder. The argument can have any name.

How columns are resolved

Column names from enums (e.g. CREATED_AT) and arguments (minAge) are mapped to real columns through one central rule (Lighthouse::Support::Naming): ALLCAPS enum keys are downcased, and camelCase is converted to snake_case. This keeps client-facing GraphQL idiomatic while matching your Rails schema. An enum value's @enum(value:) names its column directly, as in the enums @orderBy and @whereConditions generate.

Edit this page on GitHub
Prev
Relationships
Next
Mutations