Skip to content

Commit

Permalink
add efficient index for quickly finding billable metrics with an expr…
Browse files Browse the repository at this point in the history
…ession
  • Loading branch information
nudded committed Oct 18, 2024
1 parent aac3bbe commit 121c83e
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 5 deletions.
3 changes: 3 additions & 0 deletions app/models/billable_metric.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ class BillableMetric < ApplicationRecord

default_scope -> { kept }

scope :with_expression, -> { where("expression IS NOT NULL AND expression <> ''") }

def self.ransackable_attributes(_auth_object = nil)
%w[name code]
end
Expand Down Expand Up @@ -108,6 +110,7 @@ def validate_expression
# Indexes
#
# index_billable_metrics_on_deleted_at (deleted_at)
# index_billable_metrics_on_org_id_and_code_and_expr (organization_id,code,expression) WHERE ((expression IS NOT NULL) AND ((expression)::text <> ''::text))
# index_billable_metrics_on_organization_id (organization_id)
# index_billable_metrics_on_organization_id_and_code (organization_id,code) UNIQUE WHERE (deleted_at IS NULL)
#
Expand Down
5 changes: 1 addition & 4 deletions app/services/events/create_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,9 @@ def call
attr_reader :organization, :params, :timestamp, :metadata

def pre_ingest(event)
# TODO: make this efficient
bm = organization.billable_metrics.find_by(code: event.code)
bm = organization.billable_metrics.with_expression.find_by(code: event.code)
return unless bm

return if bm.expression.blank?

evaluation_event = Lago::Event.new(event.code, event.timestamp.to_i, event.properties)

value = Lago::ExpressionParser.parse(bm.expression)&.evaluate(evaluation_event)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# frozen_string_literal: true

class AddExpressionIndexToBillableMetrics < ActiveRecord::Migration[7.1]
disable_ddl_transaction!
def change
add_index :billable_metrics, [:organization_id, :code, :expression],
name: 'index_billable_metrics_on_org_id_and_code_and_expr',
algorithm: :concurrently,
where: "expression IS NOT NULL AND expression <> ''"
end
end
3 changes: 2 additions & 1 deletion db/schema.rb

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 121c83e

Please sign in to comment.