Skip to content

Commit 50277f4

Browse files
authored
perf(graphql): make sub-aggregations that group on leaf-backed object fields more efficient (#1461)
**Why.** Make sub-aggregation queries that group on leaf-backed object fields (such as the Apollo entity refs from #1453) as efficient as other scalar groupings. A grouping without a missing value placeholder needs a separate `missing` aggregation at every level of a sub-aggregation, so the number of aggregations grows exponentially and can exceed the max clause count (#882). This is an alternative to #1454, which fixes the same bug by recording a type name on every leaf index field (about 640 lines per `runtime_metadata.yaml`). This PR records the type name only on the grouped-by fields of object-typed fields backed by a leaf index field: 6 lines in `artifacts_with_apollo` and 1 in `artifacts`. Stacked on #1456, which adds the assertions on `missing` aggregations that this PR updates. **How.** The schema definition records the type of the backing leaf index field. The GraphQL layer looks up that type and uses its existing missing value placeholder, so placeholder resolution (`$SECURE_RANDOM_VALUE`, enums) stays in `Schema::Type`. - `GraphQLField` runtime metadata gets an optional `object_grouping_leaf_type_name`. - `Field#define_grouped_by_field` sets it when the original field has an object type and the grouped-by field's `name_in_index` resolves, from the original field's parent type, to a leaf index field. - The path lookup from `backing_indexing_field` moves to `HasIndices#indexing_field_at`, so the grouped-by code can resolve the grouped-by field's `name_in_index` from the original field's parent type. `f.backing_indexing_field` can't be used: it resolves from the derived `GroupedBy` type, which has no indexing fields. - `Schema::Field#object_grouping_leaf_type` looks up the type (nil when unset), and the query adapter uses that type's placeholder for the grouping on a leaf-backed field. **Verification.** The Apollo entity ref test from #1456 no longer uses a `missing` aggregation. The leaf-backed query adapter tests, including a new `Boolean` case with no placeholder, fail without the fix. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
2 parents 34ad53d + 37fdcdd commit 50277f4

18 files changed

Lines changed: 214 additions & 39 deletions

File tree

‎config/schema/artifacts_with_apollo/runtime_metadata.yaml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4026,6 +4026,7 @@ object_types_by_name:
40264026
name: object_with_lookahead
40274027
listed_owner:
40284028
name_in_index: owner_ids
4029+
object_grouping_leaf_type_name: ID
40294030
resolver:
40304031
config:
40314032
exposed_id_field: token
@@ -4035,6 +4036,7 @@ object_types_by_name:
40354036
name: object_with_lookahead
40364037
owner:
40374038
name_in_index: owner_id
4039+
object_grouping_leaf_type_name: ID
40384040
resolver:
40394041
config:
40404042
exposed_id_field: token
@@ -5886,6 +5888,7 @@ object_types_by_name:
58865888
name: object_with_lookahead
58875889
listed_owner:
58885890
name_in_index: owner_ids
5891+
object_grouping_leaf_type_name: ID
58895892
resolver:
58905893
config:
58915894
exposed_id_field: token
@@ -5907,6 +5910,7 @@ object_types_by_name:
59075910
name: object_with_lookahead
59085911
owner:
59095912
name_in_index: owner_id
5913+
object_grouping_leaf_type_name: ID
59105914
resolver:
59115915
config:
59125916
exposed_id_field: token
@@ -7155,6 +7159,7 @@ object_types_by_name:
71557159
name: object_with_lookahead
71567160
sponsor:
71577161
name_in_index: sponsor_id
7162+
object_grouping_leaf_type_name: ID
71587163
resolver:
71597164
config:
71607165
exposed_id_field: id

‎elasticgraph-apollo/spec/integration/elastic_graph/apollo/graphql/apollo_entity_ref_resolver_spec.rb‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ module GraphQL
6666
)
6767
end
6868

69-
it "groups by an entity ref field in a sub-aggregation, including a group for the missing id", :expect_missing_aggregations do
69+
it "groups by an entity ref field in a sub-aggregation, including a group for the missing id" do
7070
sponsorship = ->(sponsor_id) { build(:sponsorship, sponsor_id: sponsor_id) }
7171
players = ->(*sponsor_ids) { [build(:player, affiliations: build(:affiliations, sponsorships: sponsor_ids.map(&sponsorship)))] }
7272
index_records(
@@ -104,7 +104,6 @@ module GraphQL
104104
{"grouped_by" => {"the_sponsor" => {"id" => "s2"}}, "count_detail" => {"approximate_value" => 1}},
105105
{"grouped_by" => {"the_sponsor" => nil}, "count_detail" => {"approximate_value" => 1}}
106106
)
107-
expect_last_query_to_use_missing_aggregations_on(["current_players_nested.affiliations.sponsorships_nested.sponsor_id"])
108107
end
109108

110109
it "groups list entity references on individual ids without counting duplicate ids twice per document" do

‎elasticgraph-apollo/spec/unit/elastic_graph/apollo/schema_definition_spec.rb‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -755,7 +755,8 @@ def self.with_both_casing_forms(&block)
755755
results.runtime_metadata.object_types_by_name.fetch("WidgetGroupedBy").graphql_fields_by_name.fetch("component1")
756756
).to eq(graphql_field_with(
757757
name_in_index: "component_id",
758-
resolver: configured_graphql_resolver(:apollo_entity_grouped_by_ref, exposed_id_field: "the_id_field")
758+
resolver: configured_graphql_resolver(:apollo_entity_grouped_by_ref, exposed_id_field: "the_id_field"),
759+
object_grouping_leaf_type_name: "ID"
759760
))
760761
end
761762

@@ -930,7 +931,8 @@ def self.with_both_casing_forms(&block)
930931
results.runtime_metadata.object_types_by_name.fetch("WidgetGroupedBy").graphql_fields_by_name.fetch("component")
931932
).to eq(graphql_field_with(
932933
name_in_index: "component_ids",
933-
resolver: configured_graphql_resolver(:apollo_entity_grouped_by_ref, exposed_id_field: "the_id_field")
934+
resolver: configured_graphql_resolver(:apollo_entity_grouped_by_ref, exposed_id_field: "the_id_field"),
935+
object_grouping_leaf_type_name: "ID"
934936
))
935937
end
936938

‎elasticgraph-graphql/lib/elastic_graph/graphql/aggregation/query_adapter.rb‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,8 @@ def build_groupings_from(node_node, aggregation_name, index_definitions:, from_f
233233
elsif indexed_as_leaf_field?(field_path, index_definitions)
234234
# A custom resolver can expose a single indexed value as an object. We group on that value
235235
# rather than on the selected subfields, which have no values of their own in the index.
236-
[FieldTermGrouping.new(field_path: field_path, missing_value_placeholder: nil)]
236+
leaf_type = field.object_grouping_leaf_type # : Schema::Type
237+
[FieldTermGrouping.new(field_path: field_path, missing_value_placeholder: leaf_type.grouping_missing_value_placeholder)]
237238
end
238239
end
239240
end

‎elasticgraph-graphql/lib/elastic_graph/graphql/schema/field.rb‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,20 @@ def initialize(schema, parent_type, graphql_field, runtime_metadata, resolvers_n
3737
end
3838
@resolver = runtime_metadata&.resolver
3939
@name_in_index = runtime_metadata&.name_in_index || name
40+
@object_grouping_leaf_type_name = runtime_metadata&.object_grouping_leaf_type_name
4041
@graphql_field.extras([:lookahead]) if resolvers_needing_lookahead.include?(@resolver&.name)
4142
end
4243

4344
def type
4445
@type ||= @schema.type_from(@graphql_field.type)
4546
end
4647

48+
# The type of the leaf index field backing an object-typed grouped-by field (such as an Apollo entity ref).
49+
# Nil for all other fields.
50+
def object_grouping_leaf_type
51+
@object_grouping_leaf_type ||= @object_grouping_leaf_type_name&.then { |name| @schema.type_named(name) }
52+
end
53+
4754
def name
4855
@name ||= @graphql_field.name
4956
end

‎elasticgraph-graphql/sig/elastic_graph/graphql/schema/field.rbs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ module ElasticGraph
1313
attr_reader function_adapter: Aggregation::FunctionAdapter::adapter?
1414
attr_reader relation: SchemaArtifacts::RuntimeMetadata::Relation
1515
attr_reader resolver: SchemaArtifacts::RuntimeMetadata::ConfiguredGraphQLResolver?
16+
def object_grouping_leaf_type: () -> Type?
1617

1718
def aggregated?: () -> bool
1819
def sort_clauses_for: (::Array[::String]) -> ::Array[::Hash[::String, ::Hash[::String, ::String]]]

‎elasticgraph-graphql/spec/unit/elastic_graph/graphql/aggregation/query_adapter_spec.rb‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -775,7 +775,7 @@ def build_sub_aggregation_query(args, default_page_size:, max_page_size:)
775775
name: "widget_aggregations",
776776
computations: [],
777777
groupings: [
778-
field_term_grouping_of("amount_cents", field_names_in_graphql_query: ["price"], missing_value_placeholder: nil)
778+
field_term_grouping_of("amount_cents", field_names_in_graphql_query: ["price"], missing_value_placeholder: MISSING_NUMERIC_PLACEHOLDER)
779779
]
780780
)])
781781
end
@@ -797,7 +797,7 @@ def build_sub_aggregation_query(args, default_page_size:, max_page_size:)
797797
name: "widget_aggregations",
798798
computations: [],
799799
groupings: [
800-
field_term_grouping_of("part", "part_amount_cents", field_names_in_graphql_query: ["part", "price"], missing_value_placeholder: nil)
800+
field_term_grouping_of("part", "part_amount_cents", field_names_in_graphql_query: ["part", "price"], missing_value_placeholder: MISSING_NUMERIC_PLACEHOLDER)
801801
]
802802
)])
803803
end
@@ -823,13 +823,31 @@ def build_sub_aggregation_query(args, default_page_size:, max_page_size:)
823823
nested_sub_aggregation_of(path_in_index: ["parts_nested"], query: sub_aggregation_query_of(
824824
name: "parts_nested",
825825
groupings: [
826-
field_term_grouping_of("parts_nested", "part_amount_cents", field_names_in_graphql_query: ["parts_nested", "price"], missing_value_placeholder: nil)
826+
field_term_grouping_of("parts_nested", "part_amount_cents", field_names_in_graphql_query: ["parts_nested", "price"], missing_value_placeholder: MISSING_NUMERIC_PLACEHOLDER)
827827
]
828828
))
829829
])])
830830
end
831831
end
832832

833+
context "with an object grouping field backed by a leaf field that has no missing value placeholder" do
834+
before(:context) do
835+
self.schema_artifacts = generate_schema_artifacts_with_cost_fields(
836+
customize_widget_cost: ->(field) { field.customize_grouped_by_field { |gf| gf.name_in_index = "is_draft" } }
837+
)
838+
end
839+
840+
it "groups on the field itself, with no missing value placeholder" do
841+
expect(aggregations_grouped_by_cost).to eq([aggregation_query_of(
842+
name: "widget_aggregations",
843+
computations: [],
844+
groupings: [
845+
field_term_grouping_of("is_draft", field_names_in_graphql_query: ["price"], missing_value_placeholder: nil)
846+
]
847+
)])
848+
end
849+
end
850+
833851
context "with an object grouping field backed by an object field in the index" do
834852
before(:context) do
835853
self.schema_artifacts = generate_schema_artifacts_with_cost_fields
@@ -2086,6 +2104,7 @@ def generate_schema_artifacts_with_cost_fields(customize_widget_cost: nil, custo
20862104
schema.object_type "Widget" do |type|
20872105
type.field "id", "ID!"
20882106
type.field "amount_cents", "Int"
2107+
type.field "is_draft", "Boolean"
20892108
type.field "cost", "Money", &customize_widget_cost
20902109
type.field "part", "Part"
20912110
type.field "parts_nested", "[Part!]!" do |field|

‎elasticgraph-graphql/spec/unit/elastic_graph/graphql/schema/field_spec.rb‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,52 @@ def field_of_type(type_name)
277277
end
278278
end
279279

280+
describe "#object_grouping_leaf_type" do
281+
let(:schema) do
282+
define_schema do |s|
283+
s.object_type "Person" do |t|
284+
t.field "name", "String"
285+
end
286+
287+
s.object_type "Address" do |t|
288+
t.field "city", "String"
289+
end
290+
291+
s.object_type "Photo" do |t|
292+
t.field "id", "ID!"
293+
t.field "photographer_id", "ID"
294+
t.field "photographer", "Person", name_in_index: "photographer_id", graphql_only: true
295+
t.field "address", "Address"
296+
t.index "photos"
297+
end
298+
end
299+
end
300+
301+
it "returns the type of the leaf index field backing an object-typed grouped-by field" do
302+
field = schema.field_named("PhotoGroupedBy", "photographer")
303+
304+
expect(field.object_grouping_leaf_type).to be schema.type_named("ID")
305+
end
306+
307+
it "returns nil for other fields, including the non-grouping field backed by the same leaf index field" do
308+
leaf_types_by_field = {
309+
"PhotoGroupedBy.photographer_id" => schema.field_named("PhotoGroupedBy", "photographer_id"),
310+
"PhotoGroupedBy.address" => schema.field_named("PhotoGroupedBy", "address"),
311+
"Photo.photographer" => schema.field_named("Photo", "photographer"),
312+
"Photo.address" => schema.field_named("Photo", "address"),
313+
"Photo.photographer_id" => schema.field_named("Photo", "photographer_id")
314+
}.transform_values(&:object_grouping_leaf_type)
315+
316+
expect(leaf_types_by_field).to eq({
317+
"PhotoGroupedBy.photographer_id" => nil,
318+
"PhotoGroupedBy.address" => nil,
319+
"Photo.photographer" => nil,
320+
"Photo.address" => nil,
321+
"Photo.photographer_id" => nil
322+
})
323+
end
324+
end
325+
280326
describe "#args_to_schema_form" do
281327
let(:field) do
282328
define_schema do |s|

‎elasticgraph-schema_artifacts/lib/elastic_graph/schema_artifacts/runtime_metadata/graphql_field.rb‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,19 +13,24 @@ module ElasticGraph
1313
module SchemaArtifacts
1414
module RuntimeMetadata
1515
# @private
16-
class GraphQLField < ::Data.define(:name_in_index, :relation, :computation_function, :resolver)
17-
EMPTY = new(nil, nil, nil, nil)
16+
#
17+
# `object_grouping_leaf_type_name` is only set on an object-typed grouped-by field backed by a leaf index field
18+
# (such as an Apollo entity ref). It is the type name of that leaf index field.
19+
class GraphQLField < ::Data.define(:name_in_index, :relation, :computation_function, :resolver, :object_grouping_leaf_type_name)
20+
EMPTY = new(nil, nil, nil, nil, nil)
1821
NAME_IN_INDEX = "name_in_index"
1922
RELATION = "relation"
2023
COMPUTATION_FUNCTION = "computation_function"
2124
RESOLVER = "resolver"
25+
OBJECT_GROUPING_LEAF_TYPE_NAME = "object_grouping_leaf_type_name"
2226

2327
def self.from_hash(hash)
2428
new(
2529
name_in_index: hash[NAME_IN_INDEX],
2630
relation: hash[RELATION]&.then { |rel_hash| Relation.from_hash(rel_hash) },
2731
computation_function: hash[COMPUTATION_FUNCTION]&.to_sym,
28-
resolver: hash[RESOLVER]&.then { |res_hash| ConfiguredGraphQLResolver.from_hash(res_hash) }
32+
resolver: hash[RESOLVER]&.then { |res_hash| ConfiguredGraphQLResolver.from_hash(res_hash) },
33+
object_grouping_leaf_type_name: hash[OBJECT_GROUPING_LEAF_TYPE_NAME]
2934
)
3035
end
3136

@@ -34,6 +39,7 @@ def to_dumpable_hash
3439
# Keys here are ordered alphabetically; please keep them that way.
3540
COMPUTATION_FUNCTION => computation_function&.to_s,
3641
NAME_IN_INDEX => name_in_index,
42+
OBJECT_GROUPING_LEAF_TYPE_NAME => object_grouping_leaf_type_name,
3743
RELATION => relation&.to_dumpable_hash,
3844
RESOLVER => resolver&.to_dumpable_hash
3945
}
@@ -47,6 +53,7 @@ def needed?(name_in_graphql)
4753
!!computation_function ||
4854
name_in_index&.!=(name_in_graphql) ||
4955
!resolver.nil? ||
56+
!object_grouping_leaf_type_name.nil? ||
5057
false
5158
end
5259
end

‎elasticgraph-schema_artifacts/sig/elastic_graph/schema_artifacts/runtime_metadata/graphql_field.rbs‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,24 +6,27 @@ module ElasticGraph
66
attr_reader relation: Relation?
77
attr_reader computation_function: ::Symbol?
88
attr_reader resolver: ConfiguredGraphQLResolver?
9+
attr_reader object_grouping_leaf_type_name: ::String?
910

1011
def initialize: (
1112
name_in_index: ::String?,
1213
relation: Relation?,
1314
computation_function: ::Symbol?,
14-
resolver: ConfiguredGraphQLResolver?
15+
resolver: ConfiguredGraphQLResolver?,
16+
object_grouping_leaf_type_name: ::String?
1517
) -> void
1618

1719
def with: (
1820
?name_in_index: ::String?,
1921
?relation: Relation?,
2022
?computation_function: ::Symbol?,
21-
?resolver: ConfiguredGraphQLResolver?
23+
?resolver: ConfiguredGraphQLResolver?,
24+
?object_grouping_leaf_type_name: ::String?
2225
) -> instance
2326

2427
def self.new:
25-
(name_in_index: ::String?, relation: Relation?, computation_function: ::Symbol?, resolver: ConfiguredGraphQLResolver?) -> instance
26-
| (::String?, Relation?, ::Symbol?, ConfiguredGraphQLResolver?) -> instance
28+
(name_in_index: ::String?, relation: Relation?, computation_function: ::Symbol?, resolver: ConfiguredGraphQLResolver?, object_grouping_leaf_type_name: ::String?) -> instance
29+
| (::String?, Relation?, ::Symbol?, ConfiguredGraphQLResolver?, ::String?) -> instance
2730
end
2831

2932
class GraphQLField < GraphQLFieldSupertype
@@ -32,6 +35,7 @@ module ElasticGraph
3235
RELATION: "relation"
3336
COMPUTATION_FUNCTION: "computation_function"
3437
RESOLVER: "resolver"
38+
OBJECT_GROUPING_LEAF_TYPE_NAME: "object_grouping_leaf_type_name"
3539

3640
def self.from_hash: (::Hash[::String, untyped]) -> GraphQLField
3741
def to_dumpable_hash: () -> ::Hash[::String, untyped]

0 commit comments

Comments
 (0)