search

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2021 License: MIT Imports: 4 Imported by: 1

README

Go Report Card Godoc Releases LICENSE

Package search provides a mechanism for searching across structures using the Levenshtein distance method, commonly referred to as "fuzzy" searching.

Usage & Examples

Examples can be found on the documentation for the library

Documentation

Overview

Package search provides a mechanism for searching fields within structures using the Levenshtein distance method, commonly referred to as "fuzzy" searching.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

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

Search describes a search instance with loaded objects. Multiple individual queries can be performed against a single search instance.

func (*Search) Feed

func (s *Search) Feed(o interface{}, fields ...string)

Feed will load searchable data into the instance. Not all objects fed into the search need to be of the same type, However `o` must be a struct which must contain each field specified, otherwise it will panic. Specified fields should be a string or a []string, other types may not work as expected.

func (*Search) Search

func (s *Search) Search(query string) []interface{}

Search will query the data and return a ordered list of matching objects, or an empty slice. Searches are case-insensitive.

Example
package main

import (
	"fmt"

	"github.com/ecnepsnai/search"
)

func main() {
	type Fruit struct {
		ID           int
		Name         string
		Translations []string
	}
	type Vegetable struct {
		ID           int
		Name         string
		Translations []string
	}

	fruits := []Fruit{
		{
			ID:           1,
			Name:         "Apple",
			Translations: []string{"Pomme", "Manzana"},
		},
		{
			ID:           2,
			Name:         "Banana",
			Translations: []string{"Banane", "Plátano"},
		},
	}
	vegetables := []Vegetable{
		{
			ID:           1,
			Name:         "Broccoli",
			Translations: []string{"Brocoli", "Brócoli"},
		},
		{
			ID:           2,
			Name:         "Carrot",
			Translations: []string{"Carotte", "Zanahoria"},
		},
	}

	s := search.Search{}
	for _, fruit := range fruits {
		s.Feed(fruit, "Name", "Translations")
	}
	for _, vegetable := range vegetables {
		s.Feed(vegetable, "Name", "Translations")
	}

	results := s.Search("z")

	for _, result := range results {
		if fruit, isFruit := result.(Fruit); isFruit {
			fmt.Printf("Fruit: id=%d name=%s\n", fruit.ID, fruit.Name)
		}
		if vegetable, isVegetable := result.(Vegetable); isVegetable {
			fmt.Printf("Vegetable: id=%d name=%s\n", vegetable.ID, vegetable.Name)
		}
	}

}
Output:
Vegetable: id=2 name=Carrot
Fruit: id=1 name=Apple

Jump to

Keyboard shortcuts

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