Class: ElasticGraph::GraphQL::Resolvers::QuerySource

Inherits:
GraphQL::Dataloader::Source
  • Object
show all
Defined in:
lib/elastic_graph/graphql/resolvers/query_source.rb

Overview

Provides a way to avoid N+1 query problems by batching up multiple datastore queries into one ‘msearch` call. In general, it is recommended that you use this from any resolver that needs to query the datastore, to maximize our ability to combine multiple datastore requests. Importantly, this should never be instantiated directly; instead use the `execute` method from below.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(datastore_router, query_tracker) ⇒ QuerySource

Returns a new instance of QuerySource.



20
21
22
23
# File 'lib/elastic_graph/graphql/resolvers/query_source.rb', line 20

def initialize(datastore_router, query_tracker)
  @datastore_router = datastore_router
  @query_tracker = query_tracker
end

Class Method Details

.execute_many(queries, for_context:) ⇒ Object



31
32
33
34
35
36
37
38
# File 'lib/elastic_graph/graphql/resolvers/query_source.rb', line 31

def self.execute_many(queries, for_context:)
  datastore_router = for_context.fetch(:datastore_search_router)
  query_tracker = for_context.fetch(:elastic_graph_query_tracker)
  dataloader = for_context.dataloader

  responses = dataloader.with(self, datastore_router, query_tracker).load_all(queries)
  queries.zip(responses).to_h
end

.execute_one(query, for_context:) ⇒ Object



40
41
42
# File 'lib/elastic_graph/graphql/resolvers/query_source.rb', line 40

def self.execute_one(query, for_context:)
  execute_many([query], for_context: for_context).fetch(query)
end

Instance Method Details

#fetch(queries) ⇒ Object



25
26
27
28
29
# File 'lib/elastic_graph/graphql/resolvers/query_source.rb', line 25

def fetch(queries)
  responses_by_query = @datastore_router.msearch(queries, query_tracker: @query_tracker)
  @query_tracker.record_datastore_queries_for_single_request(queries)
  queries.map { |q| responses_by_query[q] }
end