folder

package module
v0.0.0-...-6a28869 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2021 License: BSD-3-Clause Imports: 18 Imported by: 1

README

Folder

Folder is a search engine that can be embedded into Go programs or web apps via WebAssembly.

Example

package main

import (
	"fmt"
	"log"

	"github.com/veeableful/folder"
)

func main() {
	index := folder.New()

	// Prepare the documents
	firstDocument := map[string]interface{}{
		"title": "Folder is a tiny little static search engine",
		"author": map[string]interface{}{
			"name": "Chae-Young Song",
			"hobbies": []string{"drawing", "gaming", "swimming"},
		},
	}
	secondDocument := map[string]interface{}{
		"title": "Folder v0.1.0 has been released!",
		"author": map[string]interface{}{
			"name": "Lilis Iskandar",
			"hobbies": []string{"cooking", "gardening", "hiking"},
		},
	}

	// Index the documents
	index.Index(firstDocument)
	index.Index(secondDocument)

	// Save the index to disk
	err := index.SaveToShards("index", 5)
	if err != nil {
		log.Fatal(err)
	}

	// Load the index from disk
	index, err = folder.LoadDeferred("index")
	if err != nil {
		log.Fatal(err)
	}

	// Search the index
	searchResult, err := index.Search("chaeyoung drawing")
	if err != nil {
		log.Fatal(err)
	}

	// Print the search results
	for _, hit := range searchResult.Hits {
		fmt.Println(hit.Source)
	}
}

File formats

These file formats are not final and may change in the future.

shard_count

Contains the number of shards in the index.

fns

Newline-separated list of fields. Nested fields are joined together with their parent fields by dots.

dcs

Contains the documents in CSV format.

tst

Contains the term stats in CSV format.

Development

Structure
  • Main APIs are located in folder.go.
  • APIs that deal with I/O are located in io.go to separate core operations such as indexing / searching from I/O operations such as saving and loading indexes.
  • Internal code that may change often are located in internal.go.
  • Short utility functions are located in util.go.
  • Scripts are located inside the scripts directory.
  • Command-line tool packages such as folder are located inside the cmd directory.
  • Assets such as sample data files are located inside the assets directory.
Setting up

For the development of this library, first we run go generate which runs a script that install the command-line tool and fetch additional, large files for indexing and testing.

To speed up testing of new code, we may also change where github.com/veeableful/folder points to by putting the following line in the go.mod files:

replace github.com/veeableful/folder => [your Folder directory path]

The project is not currently structured for development in Windows as the scripts are shell scripts only.

Contributions

Contributions in any form are most welcome as I'm not familiar with search engine implementations myself and I don't have a CS degree. Nothing in this project is final so any kind of feedback or advice would be appreciated!

License

Folder is BSD 3-clause licensed.

Documentation

Index

Constants

View Source
const (
	FieldNamesFileExtension = "fns"
	DocumentsFileExtension  = "dcs"
	TermStatsFileExtension  = "tst"
	ShardCountFileName      = "shard_count"
)

Variables

View Source
var DefaultSearchOptions = SearchOptions{
	UseCache: true,
	Size:     10,
	From:     0,
}

DefaultSearchOptions returns the default search options.

View Source
var (
	// ErrDocumentMissingIDField is returned when the document being indexed is missing a field that
	// is specified by the user to be used as the document ID.
	ErrDocumentMissingIDField = errors.New("document missing id field")
)

Functions

func LowercaseFilter

func LowercaseFilter(tokens []string) (filteredTokens []string)

LowercaseFilter converts the tokens into their lowercase counterparts

func PunctuationFilter

func PunctuationFilter(tokens []string) (filteredTokens []string)

PunctuationFilter removes punctuations from tokens

func StopWordFilter

func StopWordFilter(tokens []string) (filteredTokens []string)

StopWordFilter removes tokens that are stop words

Types

type Empty

type Empty struct{}

type Hit

type Hit struct {
	ID     string
	Score  float64
	Source map[string]interface{}
}

Hit contains metadata of a document such as its ID and score, and also the document iself.

type IDScores

type IDScores struct {
	IDs    sort.StringSlice
	Scores sort.Float64Slice
}

IDScores is a structure used for sorting document IDs using their respective scores.

func (IDScores) Len

func (ids IDScores) Len() int

Len returns the number of document IDs.

func (IDScores) Less

func (ids IDScores) Less(i, j int) bool

Less compares the scores between two documents.

func (IDScores) Swap

func (ids IDScores) Swap(i, j int)

Swap swaps two documents and their respective scores in the arrays.

type Index

type Index struct {
	Name                  string
	FieldNames            []string
	Documents             map[string]map[string]interface{}
	TermStats             map[string]TermStat
	LoadedDocumentsShards map[uint32]struct{}
	LoadedTermStatsShards map[uint32]struct{}
	ShardCount            int
	// contains filtered or unexported fields
}

Index contains all the information needed to search and return matching documents.

func Load

func Load(indexName string) (index *Index, err error)

Load loads an index from files

func LoadDeferred

func LoadDeferred(indexName string) (index *Index, err error)

LoadDeferred loads an index metadata only the rest of the data is loaded when needed.

func LoadDeferredFS

func LoadDeferredFS(f fs.FS, indexName string) (index *Index, err error)

LoadDeferredFS loads an index metadata only the rest of the data is loaded when needed.

func LoadFS

func LoadFS(f fs.FS, indexName string) (index *Index, err error)

LoadFS loads an index from files using FS

func LoadWithProgressFS

func LoadWithProgressFS(f fs.FS, indexName string, progressCallback ProgressCallback, sleepDuration time.Duration) (index *Index, err error)

LoadWithProgressFS loads the entire index however user can monitor progress by passing a progress callback and also specify sleep duration between each shard.

func New

func New() (index *Index)

New creates an empty index.

func (*Index) Analyze

func (index *Index) Analyze(s string) (tokens []string)

AnalyzeString breaks down string into list of tokens with some metadata such positions.

func (*Index) CalculateScore

func (index *Index) CalculateScore(documentID string, tokens []string) (score float64, err error)

func (*Index) CalculateShardID

func (index *Index) CalculateShardID(s string) (shardID uint32)

func (*Index) Delete

func (index *Index) Delete(documentID string) (err error)

Delete deletes an existing document in the index.

func (*Index) Fetch

func (index *Index) Fetch(documentID string) (document map[string]interface{}, err error)

Fetch fetches a document with specific ID.

func (*Index) Index

func (index *Index) Index(document map[string]interface{}) (documentID string, err error)

Index indexes a document into the index.

func (*Index) IndexData

func (index *Index) IndexData(data []byte, dataType string) (err error)

IndexData indexes an array of bytes and assumes a certain data type such as text, JSON, or JSONL.

func (*Index) IndexDataWithIDField

func (index *Index) IndexDataWithIDField(data []byte, dataType, idField string) (err error)

IndexDataWithIDField performs similar operation as IndexData but user can provide which document field value to be used as the document ID. This is only compatible with "json" and "jsonl" data types.

func (*Index) IndexFilePath

func (index *Index) IndexFilePath(filePath, dataType string) (err error)

IndexFilePath indexes a file or directory containing files and assumes a certain data type such as text, JSON, or JSONL.

func (*Index) IndexFilePathWithIDField

func (index *Index) IndexFilePathWithIDField(filePath, dataType, idField string) (err error)

IndexFilePathWithIDField performs similar operation as IndexFilePath but user can provide which document field value to be used as the document ID. This is only compatible with "json" and "jsonl" data types.

func (*Index) IndexReader

func (index *Index) IndexReader(r io.Reader, dataType string) (err error)

IndexReader indexes a reader and assumes a certain data type such as text, JSON, or JSONL.

func (*Index) IndexReaderWithIDField

func (index *Index) IndexReaderWithIDField(r io.Reader, dataType, idField string) (err error)

IndexReaderWithIDField performs similar operation as IndexReader but user can provide which document field value to be used as the document ID. This is only compatible with "json" and "jsonl" data types.

func (*Index) IndexWithID

func (index *Index) IndexWithID(document map[string]interface{}, desiredDocumentID string) (documentID string, err error)

IndexWithID indexes a document into the index but with user-specified document ID.

func (*Index) LoadAllShards

func (index *Index) LoadAllShards(progressCallback ProgressCallback, sleepDuration time.Duration) (err error)

func (*Index) Save

func (index *Index) Save(indexName string) (err error)

func (*Index) SaveToShards

func (index *Index) SaveToShards(indexName string, shardCount int) (err error)

func (*Index) Search

func (index *Index) Search(s string) (res SearchResult, err error)

Search searches terms in an index and returns matching documents from the index along with some metadata. It is equivalent to SearchWithOptions using the default search options.

func (*Index) SearchWithOptions

func (index *Index) SearchWithOptions(s string, opts SearchOptions) (res SearchResult, err error)

SearchWithOptions searches a term just like Search but it also accepts user-provided SearchOptions.

func (*Index) Update

func (index *Index) Update(documentID string, document map[string]interface{}) (err error)

Update updates an existing document in the index with new data.

type ProgressCallback

type ProgressCallback func(loadedShardsCount, totalShardsCount int)

type SearchOptions

type SearchOptions struct {
	UseCache bool // Whether to use and/or keep relevant data in memory
	Size     int  // Number of documents to return
	From     int  // Starting offset for returned documents
}

SearchOptions contains options that can be used to alter the search operation and result.

type SearchResult

type SearchResult struct {
	Count int
	Hits  []Hit
	Time  SearchTime
}

SearchResult contains the result of a search such as matching document count, the documents themselves with some metadata (a.k.a. the hits), and the search statistics.

type SearchTime

type SearchTime struct {
	Match time.Duration
	Sort  time.Duration
	Total time.Duration
}

SearchTime contains the elapsed times during various stages in the search process.

type StringSet

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

func MakeStringSet

func MakeStringSet(a []string) StringSet

func (*StringSet) Add

func (s *StringSet) Add(v string)

func (*StringSet) Contains

func (s *StringSet) Contains(v string) (ok bool)

func (*StringSet) Intersects

func (s *StringSet) Intersects(other StringSet)

func (*StringSet) Len

func (s *StringSet) Len() int

func (*StringSet) List

func (s *StringSet) List() (a []string)

func (*StringSet) Remove

func (s *StringSet) Remove(v string)

func (*StringSet) Union

func (s *StringSet) Union(other StringSet)

type TermStat

type TermStat struct {
	TermFrequencies map[string]int
}

TermStat contains information specific to terms.

Directories

Path Synopsis
cmd
folder module

Jump to

Keyboard shortcuts

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