Class: HTM::Models::NodeRelationship

Inherits:
Object
  • Object
show all
Defined in:
lib/htm/models/node_relationship.rb

Overview

NodeRelationship model - weighted directed edge between two nodes

Edges are stored in both directions so the CTE traversal only needs WHERE source_id IN (seeds) rather than an OR across both columns.

Weights are Jaccard similarity scores for tag_cooccurrence edges:

weight = |tags(A) ∩ tags(B)| / |tags(A) ∪ tags(B)|

Constant Summary collapse

REL_TYPES =
%w[related_to supports contradicts derived_from].freeze
ORIGINS =
%w[tag_cooccurrence tag_hierarchy explicit].freeze

Instance Method Summary collapse

Instance Method Details

#before_createObject

Hooks



60
61
62
63
64
# File 'lib/htm/models/node_relationship.rb', line 60

def before_create
  self.created_at ||= Time.now
  self.updated_at ||= Time.now
  super
end

#before_saveObject



66
67
68
69
# File 'lib/htm/models/node_relationship.rb', line 66

def before_save
  self.updated_at = Time.now if changed_columns.any?
  super
end

#validateObject

Validations



26
27
28
29
30
31
32
33
34
# File 'lib/htm/models/node_relationship.rb', line 26

def validate
  super
  validates_presence %i[source_id target_id rel_type origin weight]
  validates_includes REL_TYPES, :rel_type, allow_missing: true
  validates_includes ORIGINS,   :origin,   allow_missing: true
  validates_unique %i[source_id target_id rel_type], message: 'relationship already exists'
  errors.add(:source_id, 'cannot relate a node to itself') if source_id && source_id == target_id
  errors.add(:weight, 'must be between 0.0 and 1.0') if weight && !weight.between?(0.0, 1.0)
end