Documentation
¶
Overview ¶
Package graph provides shared types and error definitions for graph processing
Package graph provides event types for graph mutation requests from rules.
Package graph provides helper functions for semantic triples-based property access. These helpers enable clean migration from dual Properties/Triples representation to pure semantic triples as the single source of truth.
Package graph provides incoming edge index types for reverse graph traversal ¶
Package graph provides types for NATS mutation API ¶
Package graph provides types for NATS mutation API ¶
Package graph provides query request/response contracts for the graph query system. These types are shared between handlers (producers) and clients (consumers) to ensure type safety and consistent API contracts.
Package graph provides index query data types for the graph query system.
Package graph provides predicate query data types for the graph query system.
Package graph provides query response type aliases for common query patterns.
Package graph provides query types for graph operations ¶
Package graph provides types for entity state storage in the graph system.
Index ¶
- Constants
- Variables
- func GetProperties(entity *EntityState) map[string]any
- func GetPropertyTriples(entity *EntityState) []message.Triple
- func GetPropertyValue(entity *EntityState, predicate string) (any, bool)
- func GetPropertyValueTyped[T any](entity *EntityState, predicate string) (T, bool)
- func GetRelationshipTriples(entity *EntityState) []message.Triple
- func HasProperty(entity *EntityState, predicate string) bool
- func MergeTriples(existing, newer []message.Triple) []message.Triple
- type AddTripleRequest
- type AddTripleResponse
- type AliasData
- type AliasQueryResponse
- type CompoundPredicateData
- type CompoundPredicateQuery
- type CompoundPredicateQueryResponse
- type ContextEntry
- type CreateEntityRequest
- type CreateEntityResponse
- type CreateEntityWithTriplesRequest
- type CreateEntityWithTriplesResponse
- type DeleteEntityRequest
- type DeleteEntityResponse
- type EntityCriteria
- type EntityState
- type Event
- func NewAlertEvent(alertType string, entityID string, properties map[string]any, ...) *Event
- func NewEntityCreateEvent(entityID string, entityType string, properties map[string]any, ...) *Event
- func NewEntityDeleteEvent(entityID string, reason string, metadata EventMetadata) *Event
- func NewEntityUpdateEvent(entityID string, properties map[string]any, metadata EventMetadata) *Event
- func NewRelationshipCreateEvent(fromID, toID string, relationshipType string, metadata EventMetadata) *Event
- func NewRelationshipDeleteEvent(fromID, toID string, relationshipType string, metadata EventMetadata) *Event
- type EventMetadata
- type EventType
- type Graphable
- type IncomingEdge
- type IncomingEdges
- func (ie *IncomingEdges) AddIncomingEdge(edge IncomingEdge)
- func (ie *IncomingEdges) Count() int
- func (ie *IncomingEdges) GetIncomingEdgesByType(edgeType string) []IncomingEdge
- func (ie *IncomingEdges) GetIncomingEntityIDs() []string
- func (ie *IncomingEdges) HasIncomingFrom(fromEntityID string) bool
- func (ie *IncomingEdges) HasIncomingOfType(edgeType string) bool
- func (ie *IncomingEdges) RemoveIncomingEdge(fromEntityID, edgeType string)
- type IncomingEntry
- type IncomingQueryResponse
- type IncomingRelationshipsData
- type MutationResponse
- type OutgoingEntry
- type OutgoingQueryResponse
- type OutgoingRelationshipsData
- type PredicateData
- type PredicateIndexEntry
- type PredicateListData
- type PredicateListQueryResponse
- type PredicateQueryResponse
- type PredicateStatsData
- type PredicateStatsQueryResponse
- type PredicateSummary
- type Provider
- type QueryDirection
- type QueryResponse
- type QueryResult
- type RelationshipCriteria
- type RemoveTripleRequest
- type RemoveTripleResponse
- type SimilarityHit
- type UpdateEntityRequest
- type UpdateEntityResponse
- type UpdateEntityWithTriplesRequest
- type UpdateEntityWithTriplesResponse
Constants ¶
const ( // Primary entity storage BucketEntityStates = "ENTITY_STATES" // Graph relationship indexes BucketPredicateIndex = "PREDICATE_INDEX" BucketIncomingIndex = "INCOMING_INDEX" BucketOutgoingIndex = "OUTGOING_INDEX" // Lookup indexes BucketAliasIndex = "ALIAS_INDEX" BucketSpatialIndex = "SPATIAL_INDEX" BucketTemporalIndex = "TEMPORAL_INDEX" BucketContextIndex = "CONTEXT_INDEX" // Semantic tier buckets BucketEmbeddingsCache = "EMBEDDINGS_CACHE" BucketEmbeddingIndex = "EMBEDDING_INDEX" BucketEmbeddingDedup = "EMBEDDING_DEDUP" BucketCommunityIndex = "COMMUNITY_INDEX" BucketAnomalyIndex = "ANOMALY_INDEX" // Structural tier buckets BucketStructuralIndex = "STRUCTURAL_INDEX" // Operational buckets BucketComponentStatus = "COMPONENT_STATUS" )
Bucket name constants for NATS KV storage
Variables ¶
var ( // ErrEntityNotFound indicates the requested entity does not exist ErrEntityNotFound = errors.New("entity not found") // ErrEntityExists indicates an entity already exists (for create operations) ErrEntityExists = errors.New("entity already exists") // ErrInvalidEntityID indicates the entity ID format is invalid ErrInvalidEntityID = errors.New("invalid entity ID") // ErrInvalidEntityData indicates the entity data is malformed ErrInvalidEntityData = errors.New("invalid entity data") // ErrVersionConflict indicates concurrent modification conflict ErrVersionConflict = errors.New("entity version conflict") )
Entity errors
var ( // ErrIndexNotFound indicates the requested index does not exist ErrIndexNotFound = errors.New("index not found") // ErrIndexCorrupted indicates index data is corrupted ErrIndexCorrupted = errors.New("index corrupted") // ErrIndexUpdateFailed indicates index update operation failed ErrIndexUpdateFailed = errors.New("index update failed") // ErrInvalidIndexKey indicates the index key format is invalid ErrInvalidIndexKey = errors.New("invalid index key") )
Index errors
var ( // ErrQueryTimeout indicates query execution exceeded timeout ErrQueryTimeout = errors.New("query timeout") // ErrQueryTooComplex indicates query exceeds complexity limits ErrQueryTooComplex = errors.New("query too complex") // ErrQueryDepthExceeded indicates traversal depth limit exceeded ErrQueryDepthExceeded = errors.New("query depth exceeded") // ErrInvalidQueryParams indicates query parameters are invalid ErrInvalidQueryParams = errors.New("invalid query parameters") )
Query errors
var ( // ErrAliasNotFound indicates the requested alias does not exist ErrAliasNotFound = errors.New("alias not found") // ErrAliasExists indicates an alias already exists ErrAliasExists = errors.New("alias already exists") // ErrInvalidAlias indicates the alias format is invalid ErrInvalidAlias = errors.New("invalid alias") )
Alias errors
var ( // ErrBufferFull indicates write buffer is at capacity ErrBufferFull = errors.New("buffer full") // ErrBatchTooBig indicates batch size exceeds limits ErrBatchTooBig = errors.New("batch too big") // ErrFlushFailed indicates buffer flush operation failed ErrFlushFailed = errors.New("flush failed") )
Buffer/batch errors
var ( // ErrNotStarted indicates service is not started ErrNotStarted = errors.New("service not started") // ErrAlreadyStarted indicates service is already started ErrAlreadyStarted = errors.New("service already started") // ErrShuttingDown indicates service is shutting down ErrShuttingDown = errors.New("service shutting down") )
Service lifecycle errors
Functions ¶
func GetProperties ¶
func GetProperties(entity *EntityState) map[string]any
GetProperties computes a properties map from entity triples. Only includes non-relationship triples (property triples). This enables backward compatibility during migration.
func GetPropertyTriples ¶
func GetPropertyTriples(entity *EntityState) []message.Triple
GetPropertyTriples returns only the property triples from entity state. These represent entity attributes/properties.
func GetPropertyValue ¶
func GetPropertyValue(entity *EntityState, predicate string) (any, bool)
GetPropertyValue retrieves a property value from entity triples by predicate. Returns the value and true if found, nil and false if not found. Only searches non-relationship triples (property triples).
func GetPropertyValueTyped ¶
func GetPropertyValueTyped[T any](entity *EntityState, predicate string) (T, bool)
GetPropertyValueTyped retrieves a property value with type assertion. Returns the typed value and true if found and type matches, zero value and false otherwise.
func GetRelationshipTriples ¶
func GetRelationshipTriples(entity *EntityState) []message.Triple
GetRelationshipTriples returns only the relationship triples from entity state. These represent edges/connections to other entities.
func HasProperty ¶
func HasProperty(entity *EntityState, predicate string) bool
HasProperty checks if entity has a property with the given predicate.
func MergeTriples ¶
MergeTriples merges triples from two slices, with newer triples taking precedence. For properties with the same predicate, newer values override older ones. For relationships, all unique relationships are preserved.
Types ¶
type AddTripleRequest ¶
type AddTripleRequest struct {
Triple message.Triple `json:"triple"`
TraceID string `json:"trace_id,omitempty"`
RequestID string `json:"request_id,omitempty"`
}
AddTripleRequest adds a triple to an existing entity
type AddTripleResponse ¶
type AddTripleResponse struct {
MutationResponse
Triple *message.Triple `json:"triple,omitempty"`
}
AddTripleResponse response for triple addition
type AliasData ¶
type AliasData struct {
CanonicalID *string `json:"canonical_id"` // nil if not found
}
AliasData contains the canonical entity ID for an alias lookup.
type AliasQueryResponse ¶
type AliasQueryResponse = QueryResponse[AliasData]
AliasQueryResponse is the response type for alias resolution queries.
type CompoundPredicateData ¶
type CompoundPredicateData struct {
Entities []string `json:"entities"`
Operator string `json:"operator"`
Matched int `json:"matched"`
}
CompoundPredicateData contains entities matching a compound predicate query.
type CompoundPredicateQuery ¶
type CompoundPredicateQuery struct {
Predicates []string `json:"predicates"`
Operator string `json:"operator"` // "AND" or "OR"
Limit int `json:"limit,omitempty"`
}
CompoundPredicateQuery represents a query combining multiple predicates.
type CompoundPredicateQueryResponse ¶
type CompoundPredicateQueryResponse = QueryResponse[CompoundPredicateData]
CompoundPredicateQueryResponse is the response type for compound predicate queries.
type ContextEntry ¶
ContextEntry represents an entity-predicate pair indexed by context.
type CreateEntityRequest ¶
type CreateEntityRequest struct {
Entity *EntityState `json:"entity"`
TraceID string `json:"trace_id,omitempty"`
RequestID string `json:"request_id,omitempty"`
}
CreateEntityRequest creates a new entity
type CreateEntityResponse ¶
type CreateEntityResponse struct {
MutationResponse
Entity *EntityState `json:"entity,omitempty"`
}
CreateEntityResponse response for entity creation
type CreateEntityWithTriplesRequest ¶
type CreateEntityWithTriplesRequest struct {
Entity *EntityState `json:"entity"`
Triples []message.Triple `json:"triples"`
TraceID string `json:"trace_id,omitempty"`
RequestID string `json:"request_id,omitempty"`
}
CreateEntityWithTriplesRequest creates entity with triples atomically
type CreateEntityWithTriplesResponse ¶
type CreateEntityWithTriplesResponse struct {
MutationResponse
Entity *EntityState `json:"entity,omitempty"`
TriplesAdded int `json:"triples_added"`
}
CreateEntityWithTriplesResponse response for atomic entity+triples creation
type DeleteEntityRequest ¶
type DeleteEntityRequest struct {
EntityID string `json:"entity_id"`
TraceID string `json:"trace_id,omitempty"`
RequestID string `json:"request_id,omitempty"`
}
DeleteEntityRequest deletes an entity
type DeleteEntityResponse ¶
type DeleteEntityResponse struct {
MutationResponse
Deleted bool `json:"deleted"`
}
DeleteEntityResponse response for entity deletion
type EntityCriteria ¶
type EntityCriteria struct {
EntityID string `json:"entity_id,omitempty"`
Type string `json:"type,omitempty"`
Properties map[string]any `json:"properties,omitempty"`
}
EntityCriteria represents criteria for querying entities
type EntityState ¶
type EntityState struct {
// ID is the 6-part entity identifier: org.platform.domain.system.type.instance
// Used as NATS KV key for storage and retrieval.
ID string `json:"id"`
// Triples contains all semantic facts about this entity.
// Properties, relationships, and domain-specific data are all stored as triples.
Triples []message.Triple `json:"triples"`
// StorageRef optionally points to where the full original message is stored.
// Supports "store once, reference anywhere" pattern for large payloads.
// Nil if message was not stored or storage reference not available.
StorageRef *message.StorageReference `json:"storage_ref,omitempty"`
// MessageType records the original message type that created/updated this entity.
// Provides provenance and enables filtering by message source.
MessageType message.Type `json:"message_type"`
// Version is incremented on each update for optimistic concurrency control.
Version uint64 `json:"version"`
// UpdatedAt records when this entity state was last modified.
UpdatedAt time.Time `json:"updated_at"`
}
EntityState represents complete local graph state for an entity. Triples are the single source of truth for all semantic properties.
The ID field is the 6-part entity identifier (org.platform.domain.system.type.instance) which serves as the NATS KV key for storage and retrieval.
To extract type information from the ID, use message.ParseEntityID():
eid, err := message.ParseEntityID(state.ID)
if err != nil {
return fmt.Errorf("invalid entity ID: %w", err)
}
entityType := eid.Type
func (*EntityState) Clone ¶
func (es *EntityState) Clone() *EntityState
Clone returns a deep copy of the EntityState. This is used to avoid race conditions when multiple goroutines process the same entity concurrently.
func (*EntityState) GetPropertyValue ¶
func (es *EntityState) GetPropertyValue(predicate string) (any, bool)
GetPropertyValue returns the value for a property by predicate. It checks Triples for a matching predicate and returns the Object value. Returns (value, true) if found, (nil, false) if not found.
type Event ¶
type Event struct {
Type EventType `json:"type"` // Event type enum
EntityID string `json:"entity_id"` // Primary entity ID
TargetID string `json:"target_id"` // Target entity ID (for relationships)
Properties map[string]any `json:"properties"` // Properties to set/update
Metadata EventMetadata `json:"metadata"` // Event metadata
Confidence float64 `json:"confidence"` // Confidence score (0.0-1.0)
}
Event represents a graph mutation request from rules. This enables an event-driven architecture where rules emit events instead of directly mutating the graph, allowing for better decoupling, auditability, and potential event replay functionality.
func NewAlertEvent ¶
func NewAlertEvent(alertType string, entityID string, properties map[string]any, metadata EventMetadata) *Event
NewAlertEvent creates an alert entity in the graph. This is commonly used by rules to create alert entities when conditions are detected. The alertType should be descriptive (e.g., "battery_low", "temperature_high").
func NewEntityCreateEvent ¶
func NewEntityCreateEvent( entityID string, entityType string, properties map[string]any, metadata EventMetadata, ) *Event
NewEntityCreateEvent creates an entity creation event. This is used when rules determine that a new entity should be created in the graph.
func NewEntityDeleteEvent ¶
func NewEntityDeleteEvent(entityID string, reason string, metadata EventMetadata) *Event
NewEntityDeleteEvent creates an entity deletion event. This is used when rules determine that an entity should be removed from the graph.
func NewEntityUpdateEvent ¶
func NewEntityUpdateEvent(entityID string, properties map[string]any, metadata EventMetadata) *Event
NewEntityUpdateEvent creates an entity update event with the specified parameters. This is a convenience constructor for the common case of updating entity properties.
func NewRelationshipCreateEvent ¶
func NewRelationshipCreateEvent(fromID, toID string, relationshipType string, metadata EventMetadata) *Event
NewRelationshipCreateEvent creates a relationship creation event between two entities. The relationshipType should be a descriptive string like "POWERED_BY", "NEAR", etc.
func NewRelationshipDeleteEvent ¶
func NewRelationshipDeleteEvent(fromID, toID string, relationshipType string, metadata EventMetadata) *Event
NewRelationshipDeleteEvent creates a relationship deletion event. This removes a relationship between two entities based on the relationship type.
func (*Event) EventType ¶
EventType returns the event type as a string. This method implements the rule.Event interface, allowing graph events to be used generically by the rule processor.
func (*Event) Payload ¶
Payload returns the event data as a generic map. This method implements the rule.Event interface, providing access to the event's properties in a generic format.
type EventMetadata ¶
type EventMetadata struct {
RuleName string `json:"rule_name"` // Name of the rule that generated this event
Timestamp time.Time `json:"timestamp"` // When the event was generated
Source string `json:"source"` // Component that generated the event
Reason string `json:"reason"` // Human-readable reason for the event
Version string `json:"version"` // Event schema version (default "1.0.0")
}
EventMetadata contains metadata about the event source and context. This information is crucial for debugging, auditing, and understanding the decision-making process of the rule system.
type EventType ¶
type EventType string
EventType defines types of graph events that can be emitted by rules.
const ( // EventEntityCreate represents a request to create a new entity in the graph. EventEntityCreate EventType = "entity_create" // EventEntityUpdate represents a request to update an existing entity's properties. EventEntityUpdate EventType = "entity_update" // EventEntityDelete represents a request to delete an entity from the graph. EventEntityDelete EventType = "entity_delete" // EventRelationshipCreate represents a request to create a relationship between entities. EventRelationshipCreate EventType = "relationship_create" // EventRelationshipDelete represents a request to delete a relationship between entities. EventRelationshipDelete EventType = "relationship_delete" )
type Graphable ¶
type Graphable interface {
// EntityID returns deterministic 6-part ID: org.platform.domain.system.type.instance
EntityID() string
// Triples returns all facts about this entity
Triples() []message.Triple
}
Graphable enables messages to self-declare their domain entities and relationships. This interface eliminates the need for brittle string matching in entity extraction by allowing payloads to explicitly state what entities they contain and how those entities relate to each other.
The Graphable pattern addresses a core architectural requirement: messages should contain domain expertise about the entities they represent. Rather than having infrastructure code guess what entities exist based on message types or field names, the message payload itself declares this information.
Design Benefits:
- Domain Expertise: Payloads contain knowledge about their entities
- Type Safety: No string matching or reflection-based entity detection
- Extensibility: New domains simply implement the interface
- Relationships: Explicit declaration of entity relationships
- Performance: No need for complex entity detection algorithms
- Resolution Guidance: Provides hints for entity resolution and merging
Triple-Based Design:
The Graphable interface uses a Triple-based approach where payloads return RDF-like triples (subject, predicate, object) to describe entity properties and relationships. This provides maximum flexibility while remaining simple.
Example Implementation:
type PositionPayload struct {
SystemID uint8 `json:"system_id"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
Altitude float32 `json:"altitude"`
}
func (p *PositionPayload) EntityID() string {
// Return deterministic 6-part ID
return fmt.Sprintf("acme.telemetry.robotics.mavlink.drone.%d", p.SystemID)
}
func (p *PositionPayload) Triples() []message.Triple {
entityID := p.EntityID()
return []message.Triple{
{Subject: entityID, Predicate: "geo.location.latitude", Object: p.Latitude},
{Subject: entityID, Predicate: "geo.location.longitude", Object: p.Longitude},
{Subject: entityID, Predicate: "geo.location.altitude", Object: p.Altitude},
}
}
Graphable provides entity identification and semantic triples
type IncomingEdge ¶
type IncomingEdge struct {
FromEntityID string `json:"from_entity_id"`
EdgeType string `json:"edge_type"`
Weight float64 `json:"weight,omitempty"`
UpdatedAt time.Time `json:"updated_at"`
}
IncomingEdge represents an edge pointing TO this entity
type IncomingEdges ¶
type IncomingEdges struct {
EntityID string `json:"entity_id"`
Incoming []IncomingEdge `json:"incoming"`
UpdatedAt time.Time `json:"updated_at"`
}
IncomingEdges tracks all entities that point TO this entity
func (*IncomingEdges) AddIncomingEdge ¶
func (ie *IncomingEdges) AddIncomingEdge(edge IncomingEdge)
AddIncomingEdge adds or updates an incoming edge
func (*IncomingEdges) Count ¶
func (ie *IncomingEdges) Count() int
Count returns the number of incoming edges
func (*IncomingEdges) GetIncomingEdgesByType ¶
func (ie *IncomingEdges) GetIncomingEdgesByType(edgeType string) []IncomingEdge
GetIncomingEdgesByType returns all incoming edges of a specific type
func (*IncomingEdges) GetIncomingEntityIDs ¶
func (ie *IncomingEdges) GetIncomingEntityIDs() []string
GetIncomingEntityIDs returns all entity IDs that have edges pointing to this entity
func (*IncomingEdges) HasIncomingFrom ¶
func (ie *IncomingEdges) HasIncomingFrom(fromEntityID string) bool
HasIncomingFrom checks if there's an incoming edge from the specified entity
func (*IncomingEdges) HasIncomingOfType ¶
func (ie *IncomingEdges) HasIncomingOfType(edgeType string) bool
HasIncomingOfType checks if there's an incoming edge of the specified type
func (*IncomingEdges) RemoveIncomingEdge ¶
func (ie *IncomingEdges) RemoveIncomingEdge(fromEntityID, edgeType string)
RemoveIncomingEdge removes an incoming edge
type IncomingEntry ¶
type IncomingEntry struct {
FromEntityID string `json:"from_entity_id"`
Predicate string `json:"predicate"`
}
IncomingEntry represents a single incoming relationship in the graph.
type IncomingQueryResponse ¶
type IncomingQueryResponse = QueryResponse[IncomingRelationshipsData]
IncomingQueryResponse is the response type for incoming relationship queries.
type IncomingRelationshipsData ¶
type IncomingRelationshipsData struct {
Relationships []IncomingEntry `json:"relationships"`
}
IncomingRelationshipsData contains incoming relationships for an entity.
type MutationResponse ¶
type MutationResponse struct {
Success bool `json:"success"`
Error string `json:"error,omitempty"`
TraceID string `json:"trace_id,omitempty"`
RequestID string `json:"request_id,omitempty"`
Timestamp int64 `json:"timestamp"` // Unix nano timestamp
KVRevision uint64 `json:"kv_revision,omitempty"` // KV bucket revision after write
}
MutationResponse is the base response for all mutations
func NewMutationResponse ¶
func NewMutationResponse(success bool, err error, traceID, requestID string) MutationResponse
NewMutationResponse creates a base mutation response
type OutgoingEntry ¶
type OutgoingEntry struct {
ToEntityID string `json:"to_entity_id"`
Predicate string `json:"predicate"`
}
OutgoingEntry represents a single outgoing relationship in the graph.
type OutgoingQueryResponse ¶
type OutgoingQueryResponse = QueryResponse[OutgoingRelationshipsData]
OutgoingQueryResponse is the response type for outgoing relationship queries.
type OutgoingRelationshipsData ¶
type OutgoingRelationshipsData struct {
Relationships []OutgoingEntry `json:"relationships"`
}
OutgoingRelationshipsData contains outgoing relationships for an entity.
type PredicateData ¶
type PredicateData struct {
Entities []string `json:"entities"`
}
PredicateData contains entities that have a specific predicate.
type PredicateIndexEntry ¶
type PredicateIndexEntry struct {
Entities []string `json:"entities"`
Predicate string `json:"predicate"`
EntityID string `json:"entity_id,omitempty"` // backward compat
}
PredicateIndexEntry represents entities that have a specific predicate.
type PredicateListData ¶
type PredicateListData struct {
Predicates []PredicateSummary `json:"predicates"`
Total int `json:"total"`
}
PredicateListData contains all predicates with their entity counts.
type PredicateListQueryResponse ¶
type PredicateListQueryResponse = QueryResponse[PredicateListData]
PredicateListQueryResponse is the response type for predicate list queries.
type PredicateQueryResponse ¶
type PredicateQueryResponse = QueryResponse[PredicateData]
PredicateQueryResponse is the response type for predicate queries.
type PredicateStatsData ¶
type PredicateStatsData struct {
Predicate string `json:"predicate"`
EntityCount int `json:"entity_count"`
SampleEntities []string `json:"sample_entities"`
}
PredicateStatsData contains detailed statistics for a single predicate.
type PredicateStatsQueryResponse ¶
type PredicateStatsQueryResponse = QueryResponse[PredicateStatsData]
PredicateStatsQueryResponse is the response type for predicate stats queries.
type PredicateSummary ¶
type PredicateSummary struct {
Predicate string `json:"predicate"`
EntityCount int `json:"entity_count"`
}
PredicateSummary represents a predicate with its entity count.
type Provider ¶
type Provider interface {
// GetAllEntityIDs returns all entity IDs in the graph.
GetAllEntityIDs(ctx context.Context) ([]string, error)
// GetNeighbors returns the entity IDs connected to the given entity.
// direction: "outgoing", "incoming", or "both"
GetNeighbors(ctx context.Context, entityID string, direction string) ([]string, error)
// GetEdgeWeight returns the weight of the edge between two entities.
// Returns 1.0 if edge exists but has no weight, 0.0 if no edge exists.
GetEdgeWeight(ctx context.Context, fromID, toID string) (float64, error)
}
Provider abstracts the graph data source for algorithms. Used by clustering, structural indexing, and other graph operations.
type QueryDirection ¶
type QueryDirection int
QueryDirection represents the direction of a query
const ( // QueryDirectionOutgoing queries outgoing edges/relationships QueryDirectionOutgoing QueryDirection = iota // QueryDirectionIncoming queries incoming edges/relationships QueryDirectionIncoming // QueryDirectionBidirectional queries both directions QueryDirectionBidirectional )
func (QueryDirection) String ¶
func (qd QueryDirection) String() string
String returns the string representation of QueryDirection
type QueryResponse ¶
type QueryResponse[T any] struct { Data T `json:"data"` Error string `json:"error,omitempty"` RequestID string `json:"request_id,omitempty"` Timestamp time.Time `json:"timestamp"` }
QueryResponse is the standard envelope for all query responses. Uses generics for compile-time type safety.
func NewQueryError ¶
func NewQueryError[T any](msg string) QueryResponse[T]
NewQueryError creates an error response with the given message.
func NewQueryResponse ¶
func NewQueryResponse[T any](data T) QueryResponse[T]
NewQueryResponse creates a successful response with the given data.
type QueryResult ¶
type QueryResult struct {
Entities []map[string]any `json:"entities"`
Relationships []map[string]any `json:"relationships"`
Count int `json:"count"`
}
QueryResult represents the result of a graph query
type RelationshipCriteria ¶
type RelationshipCriteria struct {
FromID string `json:"from_id,omitempty"`
ToID string `json:"to_id,omitempty"`
Type string `json:"type,omitempty"`
Properties map[string]any `json:"properties,omitempty"`
Direction QueryDirection `json:"direction,omitempty"`
}
RelationshipCriteria represents criteria for querying relationships
type RemoveTripleRequest ¶
type RemoveTripleRequest struct {
Subject string `json:"subject"`
Predicate string `json:"predicate"`
TraceID string `json:"trace_id,omitempty"`
RequestID string `json:"request_id,omitempty"`
}
RemoveTripleRequest removes a triple from an entity
type RemoveTripleResponse ¶
type RemoveTripleResponse struct {
MutationResponse
Removed bool `json:"removed"`
}
RemoveTripleResponse response for triple removal
type SimilarityHit ¶
type SimilarityHit struct {
// EntityID is the unique identifier of the matched entity
EntityID string `json:"entity_id"`
// Similarity is the cosine similarity score (0.0-1.0, higher is more similar)
Similarity float64 `json:"similarity"`
// EntityType is the type of the entity (optional, for type-batched filtering)
EntityType string `json:"entity_type,omitempty"`
}
SimilarityHit represents an entity similarity match. Used by semantic search and clustering operations.
type UpdateEntityRequest ¶
type UpdateEntityRequest struct {
Entity *EntityState `json:"entity"`
TraceID string `json:"trace_id,omitempty"`
RequestID string `json:"request_id,omitempty"`
}
UpdateEntityRequest updates an existing entity
type UpdateEntityResponse ¶
type UpdateEntityResponse struct {
MutationResponse
Entity *EntityState `json:"entity,omitempty"`
Version int64 `json:"version,omitempty"`
}
UpdateEntityResponse response for entity update
type UpdateEntityWithTriplesRequest ¶
type UpdateEntityWithTriplesRequest struct {
Entity *EntityState `json:"entity"`
AddTriples []message.Triple `json:"add_triples,omitempty"`
RemoveTriples []string `json:"remove_triples,omitempty"` // Triple predicates to remove
TraceID string `json:"trace_id,omitempty"`
RequestID string `json:"request_id,omitempty"`
}
UpdateEntityWithTriplesRequest updates entity and modifies triples atomically
type UpdateEntityWithTriplesResponse ¶
type UpdateEntityWithTriplesResponse struct {
MutationResponse
Entity *EntityState `json:"entity,omitempty"`
TriplesAdded int `json:"triples_added"`
TriplesRemoved int `json:"triples_removed"`
Version int64 `json:"version,omitempty"`
}
UpdateEntityWithTriplesResponse response for atomic entity+triples update
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package clustering provides community detection algorithms and graph clustering for discovering structural patterns in the knowledge graph.
|
Package clustering provides community detection algorithms and graph clustering for discovering structural patterns in the knowledge graph. |
|
Package datamanager consolidates entity and edge operations into a unified data management service.
|
Package datamanager consolidates entity and edge operations into a unified data management service. |
|
Package embedding provides vector embedding generation and caching for semantic search in the knowledge graph.
|
Package embedding provides vector embedding generation and caching for semantic search in the knowledge graph. |
|
Package inference provides structural anomaly detection for missing relationships.
|
Package inference provides structural anomaly detection for missing relationships. |
|
Package llm provides LLM client abstractions for OpenAI-compatible APIs.
|
Package llm provides LLM client abstractions for OpenAI-compatible APIs. |
|
Package messagemanager provides message processing and entity extraction for the knowledge graph.
|
Package messagemanager provides message processing and entity extraction for the knowledge graph. |
|
Package query provides a clean interface for reading graph data from NATS KV buckets.
|
Package query provides a clean interface for reading graph data from NATS KV buckets. |
|
Package structural provides structural graph indexing algorithms for query optimization and inference detection.
|
Package structural provides structural graph indexing algorithms for query optimization and inference detection. |