kg

package
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 9, 2026 License: MIT Imports: 9 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package kg folds extracted triples into a knowledge graph and answers questions about its shape.

The same assertion arriving twice is one edge, not two. Nodes are keyed by the folded form of their name and edges by (subject, predicate, object), so repetition raises confidence and adds provenance rather than duplicating structure. Where a graph is kept is store's business; Mem is the in-memory default so this package and its callers work without a database.

Index

Constants

This section is empty.

Variables

View Source
var Types = []string{"type", "is_a", "isa", "instance_of", "rdf:type"}

Types are the predicates read as a statement about what a node is rather than as an edge, when Build is given no others.

Functions

func Fold

func Fold(s string) string

Fold is the canonical form of a name and the id of the node that carries it: leading, trailing and repeated whitespace removed, lower case. Two spellings that fold alike are one node.

func Hash

func Hash(s, p, o string) string

Hash is the stable identifier of an assertion: FNV-1a over the folded triple, hex. The same claim hashes the same in every process and every run, which is what naming a claim in a provenance record needs.

Types

type Edge

type Edge struct {
	From  string
	To    string
	Label string   // predicate, surface form as first asserted
	Score float64  // best confidence any assertion gave it
	Count int      // how many assertions carried it
	Docs  []string // documents that asserted it, first seen first
}

Edge is one relation asserted between two nodes.

func (Edge) ID

func (e Edge) ID() string

ID returns the stable identifier of the assertion this edge records, the name a provenance entry uses to point at the claim.

type Graph

type Graph struct {
	// contains filtered or unexported fields
}

Graph holds nodes and the edges between them. Insertion order is preserved so every listing and every traversal is reproducible.

func Build

func Build(ts []semantic.Triple, types ...string) *Graph

Build folds triples into a graph. Predicates named in types state a node's type instead of making an edge; with none given, the package Types apply. Build(nil) is the empty graph, ready for Add.

func (*Graph) Add

func (g *Graph) Add(t semantic.Triple) bool

Add asserts one triple and reports whether it said anything: a triple missing a subject, predicate or object is dropped. Repeating an assertion raises its count, keeps the highest confidence seen, and records the further source; it never makes a second edge. A zero Score counts as 1, because an extractor that states no confidence is not stating no confidence.

func (*Graph) Adj

func (g *Graph) Adj(id string) []string

Adj lists the neighbours of a node in either direction, out first.

func (*Graph) Between

func (g *Graph) Between() map[string]float64

Between scores each node by how many shortest paths run through it, over the pairs it could serve. It finds the nodes a graph would come apart without, which is not the same as the nodes with the most edges.

Brandes' accumulation: one pass per node, dependencies summed backwards along the paths that pass through.

func (*Graph) Bridges

func (g *Graph) Bridges() []Edge

Bridges are the links whose loss would split the graph further. Removing one raises the number of components by exactly one, which makes them the edges a knowledge graph can least afford to be wrong about.

This is Tarjan's rule: a link u–v bridges when nothing reachable from v without crossing it was discovered before u.

func (*Graph) Close

func (g *Graph) Close() map[string]float64

Close scores each node by how near it is to the rest: the nodes it reaches over the total distance to them. A node one step from everything scores 1, and one that reaches nothing scores 0.

func (*Graph) Degree

func (g *Graph) Degree() map[string]float64

Degree scores each node by how many neighbours it has, over the most it could have. A node joined to everything scores 1.

func (*Graph) Edges

func (g *Graph) Edges() []Edge

Edges lists every edge, first asserted first.

func (*Graph) Eigen

func (g *Graph) Eigen() map[string]float64

Eigen scores each node by the scores of its neighbours, settled by power iteration and scaled so the highest is 1. Being joined to important nodes counts for more than being joined to many.

func (*Graph) Groups

func (g *Graph) Groups() [][]string

Groups partitions the nodes into communities by moving each node to the neighbouring group that raises modularity most, until nothing moves. Nodes with no edges stay alone. Groups come back largest first.

func (*Graph) In

func (g *Graph) In(id string) []string

In lists the nodes that point at this one.

func (*Graph) Merge

func (g *Graph) Merge(into, from string) bool

Merge folds one node into another: edges, documents, properties and the higher confidence move to into, and from becomes one of its aliases. It is the mechanism an entity resolver drives — kg performs the merge, it does not decide which two names are the same thing. It reports whether anything moved.

func (*Graph) Modularity

func (g *Graph) Modularity(groups [][]string) float64

Modularity scores a partition: how much more of the graph's links fall inside its groups than chance would put there. Above about 0.3 is community structure worth believing; 0 is what random groups get.

func (*Graph) Near

func (g *Graph) Near(id string, hops int) *Graph

Near is the neighbourhood of a node: everything reachable within hops steps, ignoring direction, as a graph in its own right. Zero hops is the node alone; a node the graph does not hold gives an empty graph.

func (*Graph) Node

func (g *Graph) Node(id string) (Node, bool)

Node returns the node with an id and whether the graph has one.

func (*Graph) Nodes

func (g *Graph) Nodes() []Node

Nodes lists every node, first asserted first.

func (*Graph) Out

func (g *Graph) Out(id string) []string

Out lists the nodes this one points at.

func (*Graph) Parts

func (g *Graph) Parts() [][]string

Parts are the connected components, largest first and then in the order their first node was asserted. Every node is in exactly one.

func (*Graph) Path

func (g *Graph) Path(from, to string) []string

Path is the shortest route between two nodes, ignoring direction, as the nodes along it including both ends. It is nil when there is no route; the number of steps is one less than its length.

func (*Graph) Rank

func (g *Graph) Rank() map[string]float64

Rank is PageRank over the asserted direction: the share of a random walker's time spent at each node, following edges with probability damping and jumping anywhere with the rest. Scores sum to 1. A node with no outgoing edges hands its share to the jump rather than losing it.

func (*Graph) Set

func (g *Graph) Set(id string, props map[string]any) bool

Set records a node and its properties, creating it if this is the first the graph has heard of it, and reports whether the id was usable. Properties already present are left alone: the first writer of a value wins. It is how a node with no assertions yet — the isolated node analytics must still count — gets into the graph.

func (*Graph) Size

func (g *Graph) Size() (nodes, edges int)

Size reports how many nodes and how many edges the graph holds.

func (*Graph) Stat

func (g *Graph) Stat() Stat

Stat measures the graph.

func (*Graph) Sub

func (g *Graph) Sub(ids ...string) *Graph

Sub is the subgraph induced by a set of nodes: those nodes, and every edge with both ends among them.

type Mem

type Mem struct {
	// contains filtered or unexported fields
}

Mem keeps a graph in memory and serves it through store.Graph and store.Triple, so a caller with no database still has somewhere to put a graph. Writes go through the same merge as Add: the same assertion twice is one edge. It is safe for concurrent use, and its zero value is an empty store ready to write to.

func Keep

func Keep(g *Graph) *Mem

Keep serves an already built graph. Mem takes it over: later writes through Mem change it, so a caller that wants the original untouched passes a Sub of everything.

func (*Mem) Assert

func (m *Mem) Assert(ctx context.Context, s, p, o string) error

Assert records one triple.

func (*Mem) Edge

func (m *Mem) Edge(ctx context.Context, from, to, label string) error

Edge records a relation between two nodes, creating either that the graph has not heard of.

func (*Mem) Graph

func (m *Mem) Graph() *Graph

Graph is the graph Mem holds, for the measures in this package. It is the live graph, not a copy, and reading it while another goroutine writes is the caller's business to order.

func (*Mem) Match

func (m *Mem) Match(ctx context.Context, s, p, o string) ([][3]string, error)

Match returns the asserted triples matching a pattern, first asserted first. An empty subject, predicate or object stands for any, so Match with three empty strings returns everything.

func (*Mem) Node

func (m *Mem) Node(ctx context.Context, id string, props map[string]any) error

Node records a node and its properties.

func (*Mem) Out

func (m *Mem) Out(ctx context.Context, id string) ([]string, error)

Out lists the nodes an edge points at from this one.

type Node

type Node struct {
	ID    string         // stable key, the folded form of the name
	Name  string         // surface form, as first asserted
	Type  string         // set by a type predicate; empty until one arrives
	Score float64        // best confidence any assertion gave it
	Props map[string]any // properties, as written by a store caller
	Docs  []string       // documents that asserted it, first seen first
	Alias []string       // ids folded into this one by Merge
}

Node is one thing the graph knows about.

type Pair

type Pair struct {
	ID    string
	Score float64
}

Pair is a node and its score.

func Top

func Top(score map[string]float64, n int) []Pair

Top orders a score highest first, ties by id so the answer is the same every run. A count of zero or less returns everything.

type Span

type Span struct {
	Min int
	Max int
	Avg float64
}

Span is the low, high and mean of a distribution, used here for degree.

type Stat

type Stat struct {
	Nodes   int     // nodes
	Edges   int     // asserted edges
	Links   int     // distinct undirected links between different nodes
	Density float64 // links over the links a complete graph would have
	Deg     Span    // neighbours per node
	Parts   int     // connected components
	Biggest int     // nodes in the largest component
	Whole   bool    // one component, so everything reaches everything
	Path    float64 // mean shortest path over the pairs that have one
	Shape   string  // disconnected, sparse, moderate or dense
}

Stat is what the graph looks like from a distance.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL