vellum

package module
v0.0.0-...-e02543e Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2017 License: Apache-2.0 Imports: 12 Imported by: 0

README

vellum vellum

Build Status Coverage Status GoDoc Go Report Card License

A Go library implementing an FST (finite state transducer) capable of:

  • mapping between keys ([]byte) and a value (uint64)
  • enumerating keys in lexicographic order

Some additional goals of this implementation:

  • bounded memory use while building the FST
  • streaming out FST data while building
  • mmap FST runtime to support very large FTSs (optional)

Usage

Building an FST

To build an FST, create a new builder using the New() method. This method takes an io.Writer as an argument. As the FST is being built, data will be streamed to the writer as soon as possible. With this builder you MUST insert keys in lexicographic order. Inserting keys out of order will result in an error. After inserting the last key into the builder, you MUST call Close() on the builder. This will flush all remaining data to the underlying writer.

In memory:

  var buf bytes.Buffer
  builder, err := vellum.New(&buf, nil)
  if err != nil {
    log.Fatal(err)
  }

To disk:

  f, err := os.Create("/tmp/vellum.fst")
  if err != nil {
    log.Fatal(err)
  }
  builder, err := vellum.New(f, nil)
  if err != nil {
    log.Fatal(err)
  }

MUST insert keys in lexicographic order:

err = builder.Insert([]byte("cat"), 1)
if err != nil {
  log.Fatal(err)
}

err = builder.Insert([]byte("dog"), 2)
if err != nil {
  log.Fatal(err)
}

err = builder.Insert([]byte("fish"), 3)
if err != nil {
  log.Fatal(err)
}

err = builder.Close()
if err != nil {
  log.Fatal(err)
}
Using an FST

After closing the builder, the data can be used to instantiate an FST. If the data was written to disk, you can use the Open() method to mmap the file. If the data is already in memory, or you wish to load/mmap the data yourself, you can instantiate the FST with the Load() method.

Load in memory:

  fst, err := vellum.Load(buf.Bytes())
  if err != nil {
    log.Fatal(err)
  }

Open from disk:

  fst, err := vellum.Open("/tmp/vellum.fst")
  if err != nil {
    log.Fatal(err)
  }

Get key/value:

  val, exists, err = fst.Get([]byte("dog"))
  if err != nil {
    log.Fatal(err)
  }
  if exists {
    fmt.Printf("contains dog with val: %d\n", val)
  } else {
    fmt.Printf("does not contain dog")
  }

Iterate key/values:

  itr, err := fst.Iterator(startKeyInclusive, endKeyExclusive)
  for err == nil {
    key, val := itr.Current()
    fmt.Printf("contains key: %s val: %d", key, val)
    err = itr.Next()
  }
  if err != nil {
    log.Fatal(err)
  }
How does the FST get built?

A full example of the implementation is beyond the scope of this README, but let's consider a small example where we want to insert 3 key/value pairs.

First we insert "are" with the value 4.

step1

Next, we insert "ate" with the value 2.

step2

Notice how the values associated with the transitions were adjusted so that by summing them while traversing we still get the expected value.

At this point, we see that state 5 looks like state 3, and state 4 looks like state 2. But, we cannot yet combine them because future inserts could change this.

Now, we insert "see" with value 3. Once it has been added, we now know that states 5 and 4 can longer change. Since they are identical to 3 and 2, we replace them.

step3

Again, we see that states 7 and 8 appear to be identical to 2 and 3.

Having inserted our last key, we call Close() on the builder.

step4

Now, states 7 and 8 can safely be replaced with 2 and 3.

For additional information, see the references at the bottom of this document.

What does the serialized format look like?

We've broken out a separate document on the vellum disk format v1.

What if I want to use this on a system that doesn't have mmap?

The mmap library itself is guarded with system/architecture build tags, but we've also added an additional build tag in vellum. If you'd like to Open() a file based representation of an FST, but not use mmap, you can build the library with the nommap build tag. NOTE: if you do this, the entire FST will be read into memory.

Can I use this with Unicode strings?

Yes, however this implementation is only aware of the byte representation you choose. In order to find matches, you must work with some canonical byte representation of the string. In the future, some encoding-aware traversals may be possible on top of the lower-level byte transitions.

How did this library come to be?

In my work on the Bleve project I became aware of the power of the FST for many search-related tasks. The obvious starting point for such a thing in Go was the mafsa project. While working with mafsa I encountered some issues. First, it did not stream data to disk while building. Second, it chose to use a rune as the fundamental unit of transition in the FST, but I felt using a byte would be more powerful in the end. My hope is that higher-level encoding-aware traversals will be possible when necessary. Finally, as I reported bugs and submitted PRs I learned that the mafsa project was mainly a research project and no longer being maintained. I wanted to build something that could be used in production. As the project advanced more and more techniques from the BurntSushi/fst were adapted to our implementation.

Much credit goes to two existing projects:

Most of the original implementation here started with my digging into the internals of mafsa. As the implementation progressed, I continued to borrow ideas/approaches from the BurntSushi/fst library as well.

For a great introduction to this topic, please read the blog post Index 1,600,000,000 Keys with Automata and Rust

Documentation

Overview

Package vellum is a library for building, serializing and executing an FST (finite state transducer).

There are two distinct phases, building an FST and using it.

When building an FST, you insert keys ([]byte) and their associated value (uint64). Insert operations MUST be done in lexicographic order. While building the FST, data is streamed to an underlying Writer. At the conclusion of building, you MUST call Close() on the builder.

After completion of the build phase, you can either Open() the FST if you serialized it to disk. Alternatively, if you already have the bytes in memory, you can use Load(). By default, Open() will use mmap to avoid loading the entire file into memory.

Once the FST is ready, you can use the Contains() method to see if a keys is in the FST. You can use the Get() method to see if a key is in the FST and retrieve it's associated value. And, you can use the Iterator method to enumerate key/value pairs within a specified range.

Example
package main

import (
	"bytes"
	"fmt"
	"log"

	"github.com/couchbaselabs/vellum"
)

func main() {

	var buf bytes.Buffer
	builder, err := vellum.New(&buf, nil)
	if err != nil {
		log.Fatal(err)
	}

	err = builder.Insert([]byte("cat"), 1)
	if err != nil {
		log.Fatal(err)
	}

	err = builder.Insert([]byte("dog"), 2)
	if err != nil {
		log.Fatal(err)
	}

	err = builder.Insert([]byte("fish"), 3)
	if err != nil {
		log.Fatal(err)
	}

	err = builder.Close()
	if err != nil {
		log.Fatal(err)
	}

	fst, err := vellum.Load(buf.Bytes())
	if err != nil {
		log.Fatal(err)
	}

	val, exists, err := fst.Get([]byte("cat"))
	if err != nil {
		log.Fatal(err)
	}
	if exists {
		fmt.Println(val)
	}

	val, exists, err = fst.Get([]byte("dog"))
	if err != nil {
		log.Fatal(err)
	}
	if exists {
		fmt.Println(val)
	}

	val, exists, err = fst.Get([]byte("fish"))
	if err != nil {
		log.Fatal(err)
	}
	if exists {
		fmt.Println(val)
	}

}
Output:

1
2
3

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrIteratorDone = errors.New("iterator-done")

ErrIteratorDone is returned by Iterator/Next/Seek methods when the Current() value pointed to by the iterator is greater than the last key in this FST, or outside the configured startKeyInclusive/endKeyExclusive range of the Iterator.

View Source
var ErrOutOfOrder = errors.New("values not inserted in lexicographic order")

ErrOutOfOrder is returned when values are not inserted in lexicographic order.

Functions

This section is empty.

Types

type AlwaysMatch

type AlwaysMatch struct{}

AlwaysMatch is an Automaton implementation which always matches

func (*AlwaysMatch) Accept

func (m *AlwaysMatch) Accept(int, byte) int

Accept returns the next AlwaysMatch state

func (*AlwaysMatch) CanMatch

func (m *AlwaysMatch) CanMatch(int) bool

CanMatch always returns true

func (*AlwaysMatch) IsMatch

func (m *AlwaysMatch) IsMatch(int) bool

IsMatch always returns true

func (*AlwaysMatch) Start

func (m *AlwaysMatch) Start() int

Start returns the AlwaysMatch start state

func (*AlwaysMatch) WillAlwaysMatch

func (m *AlwaysMatch) WillAlwaysMatch(int) bool

WillAlwaysMatch always returns true

type Automaton

type Automaton interface {

	// Start returns the start state
	Start() int

	// IsMatch returns true if and only if the state is a match
	IsMatch(int) bool

	// CanMatch returns true if and only if it is possible to reach a match
	// in zero or more steps
	CanMatch(int) bool

	// WillAlwaysMatch returns true if and only if the current state matches
	// and will always match no matter what steps are taken
	WillAlwaysMatch(int) bool

	// Accept returns the next state given the input to the specified state
	Accept(int, byte) int
}

Automaton represents the general contract of a byte-based finite automaton

type Builder

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

A Builder is used to build a new FST. When possible data is streamed out to the underlying Writer as soon as possible.

func New

func New(w io.Writer, opts *BuilderOpts) (*Builder, error)

New returns a new Builder which will stream out the underlying representation to the provided Writer as the set is built.

func (*Builder) Close

func (b *Builder) Close() error

Close MUST be called after inserting all values.

func (*Builder) Insert

func (b *Builder) Insert(key []byte, val uint64) error

Insert the provided value to the set being built. NOTE: values must be inserted in lexicographical order.

type BuilderOpts

type BuilderOpts struct {
	Encoder           int
	RegistryTableSize int
	RegistryMRUSize   int
}

BuilderOpts is a structure to let advanced users customize the behavior of the builder and some aspects of the generated FST.

type FST

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

FST is an in-memory representation of a finite state transducer, capable of returning the uint64 value associated with each []byte key stored, as well as enumerating all of the keys in order.

func Load

func Load(data []byte) (*FST, error)

Load will return the FST represented by the provided byte slice.

func Open

func Open(path string) (*FST, error)

Open loads the FST stored in the provided path

func (*FST) Close

func (f *FST) Close() error

Close will unmap any mmap'd data (if managed by vellum) and it will close the backing file (if managed by vellum). You MUST call Close() for any FST instance that is created.

func (*FST) Contains

func (f *FST) Contains(val []byte) (bool, error)

Contains returns true if this FST contains the specified key.

func (*FST) Debug

func (f *FST) Debug(callback func(int, interface{}) error) error

Debug is only intended for debug purposes, it simply asks the underlying decoder visit each state, and pass it to the provided callback.

func (*FST) Get

func (f *FST) Get(input []byte) (uint64, bool, error)

Get returns the value associated with the key. NOTE: a value of zero does not imply the key does not exist, you must consult the second return value as well.

func (*FST) Iterator

func (f *FST) Iterator(startKeyInclusive, endKeyExclusive []byte) (*Iterator, error)

Iterator returns a new Iterator capable of enumerating the key/value pairs between the provided startKeyInclusive and endKeyExclusive.

func (*FST) Len

func (f *FST) Len() int

Len returns the number of entries in this FST instance.

func (*FST) Search

func (f *FST) Search(aut Automaton, startKeyInclusive, endKeyExclusive []byte) (*Iterator, error)

Search returns a new Iterator capable of enumerating the key/value pairs between the provided startKeyInclusive and endKeyExclusive that also satisfy the provided automaton.

func (*FST) Version

func (f *FST) Version() int

Version returns the encoding version used by this FST instance.

type Iterator

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

Iterator is a structure for iterating key/value pairs in this FST in lexicographic order. Iterators should be constructed with the Iterator method on the parent FST structure.

func (*Iterator) Close

func (i *Iterator) Close() error

Close will free any resources held by this iterator.

func (*Iterator) Current

func (i *Iterator) Current() ([]byte, uint64)

Current returns the key and value currently pointed to by the iterator. If the iterator is not pointing at a valid value (because Iterator/Next/Seek) returned an error previously, it may return nil,0.

func (*Iterator) Next

func (i *Iterator) Next() error

Next advances this iterator to the next key/value pair. If there is none or the advancement goes beyond the configured endKeyExclusive, then ErrIteratorDone is returned.

func (*Iterator) Seek

func (i *Iterator) Seek(key []byte) error

Seek advances this iterator to the specified key/value pair. If this key is not in the FST, Current() will return the next largest key. If this seek operation would go past the last key, or outside the configured startKeyInclusive/endKeyExclusive then ErrIteratorDone is returned.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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