google.golang.org/appengine/search 패키지(v1.6.8)

패키지 검색은 App Engine의 검색 서비스를 위한 클라이언트를 제공합니다.

기본 작업

색인은 문서를 포함합니다. 각 색인은 이름으로 식별되며 이는 사람이 읽을 수 있는 ASCII 문자열입니다.

색인 내에서 문서는 역시 사람이 읽을 수 있는 ASCII 문자열인 ID에 연결됩니다. 문서 내용은 대소문자를 구분하는 필드 이름과 값의 매핑입니다. 필드 값에 유효한 유형은 다음과 같습니다.

  • string,
  • search.Atom,
  • search.HTML,
  • time.Time(밀리초 정밀도로 저장됨)
  • float64(-2,147,483,647 과 2,147,483,647 사이의 값 포함),
  • appengine.GeoPoint.

색인에 Get 함수와 Put 메소드를 사용하면 문서가 로드되고 저장됩니다. 문서 내용은 일반적으로 구조체 포인터로 표시됩니다.

예시 코드:

type Doc struct {
    Author   string
    Comment  string
    Creation time.Time
}

index, err := search.Open("comments")
if err != nil {
    return err
}
newID, err := index.Put(ctx, "", &Doc{
    Author:   "gopher",
    Comment:  "the truth of the matter",
    Creation: time.Now(),
})
if err != nil {
    return err
}

단일 문서는 문서의 ID로 검색할 수 있습니다. 대상 구조체를 Get에 전달하면 결과 문서를 보관할 수 있습니다.

var doc Doc
err := index.Get(ctx, id, &doc)
if err != nil {
    return err
}

문서 검색 및 나열

색인에서는 Search와 List라는 두 가지 방법으로 한 번에 여러 문서를 검색할 수 있습니다.

색인에서 쿼리를 검색하면 반복기가 생성됩니다. 패키지 데이터 저장소의 반복기와 마찬가지로 대상 구조체를 Next에 전달하여 다음 결과를 디코딩합니다. 반복기가 모두 사용되면 Next가 Done을 반환합니다.

for t := index.Search(ctx, "Comment:truth", nil); ; {
    var doc Doc
    id, err := t.Next(&doc)
    if err == search.Done {
        break
    }
    if err != nil {
        return err
    }
    fmt.Fprintf(w, "%s -> %#v\n", id, doc)
}

Search는 반환할 문서를 결정하기 위해 문자열 쿼리를 사용합니다. 쿼리는 일치시킬 단일 단어처럼 단순할 수도 있고 복잡할 수도 있습니다. 쿼리 언어는 https://cloud.google.com/appengine/docs/standard/go/search/query_strings에 설명되어 있습니다.

Search는 결과가 계산되고 반환되는 방법을 보다 효율적으로 제어할 수 있는 선택적 SearchOptions 구조체도 사용합니다.

List를 호출하여 색인의 모든 문서를 반복합니다.

for t := index.List(ctx, nil); ; {
    var doc Doc
    id, err := t.Next(&doc)
    if err == search.Done {
        break
    }
    if err != nil {
        return err
    }
    fmt.Fprintf(w, "%s -> %#v\n", id, doc)
}

필드 및 속성

문서 내용은 다양한 유형으로 표시할 수 있습니다. 일반적으로 구조체 포인터가 사용되지만 FieldLoadSaver 인터페이스를 구현하는 임의 유형으로 문서 내용을 표시할 수도 있습니다. FieldLoadSaver를 사용하면 DocumentMetadata 유형의 문서에 메타데이터를 설정할 수 있습니다. 구조체 포인터는 보다 강력하게 유형이 지정되고 사용하기가 더 쉬우며 FieldLoadSaver는 더 유연합니다.

문서 내용은 필드와 속성이라는 두 가지 방법으로 표시할 수 있습니다.

필드는 문서 내용을 제공하는 가장 일반적인 방법입니다. 필드는 여러 유형의 데이터를 저장할 수 있으며 검색 시 쿼리 문자열을 사용하여 일치 항목을 찾을 수 있습니다.

속성을 사용하면 카테고리 정보를 문서에 첨부할 수 있습니다. 속성에 유효한 유일한 유형은 search.Atom 및 float64입니다. 속성을 사용하면 검색결과에 검색 시 발견한 일치 카테고리의 요약 정보를 포함하고 검색을 특정 카테고리로 제한할 수 있습니다.

기본적으로 구조체 포인터의 경우 모든 구조체 필드가 문서 필드로 사용되며, 사용되는 필드 이름이 구조체에서의 이름과 같습니다. 따라서 대문자로 시작해야 합니다. 구조체 필드에는 search:"name,options" 태그가 포함될 수 있습니다. 이름은 문자로 시작해야 하며 단어 문자로만 구성되어야 합니다. "-" 태그 이름은 해당 필드가 무시됨을 의미합니다. "facet" 옵션을 지정하면 구조체 필드가 문서 속성으로 사용됩니다. "" 옵션을 지정할 때는 쉼표를 생략할 수 있습니다. 다른 옵션은 인식되지 않습니다.

예시 코드:

// A and B are renamed to a and b.
// A, C and I are facets.
// D's tag is equivalent to having no tag at all (E).
// F and G are ignored entirely by the search package.
// I has tag information for both the search and json packages.
type TaggedStruct struct {
    A float64 `search:"a,facet"`
    B float64 `search:"b"`
    C float64 `search:",facet"`
    D float64 `search:""`
    E float64
    F float64 `search:"-"`
    G float64 `search:"-,facet"`
    I float64 `search:",facet" json:"i"`
}

FieldLoadSaver 인터페이스

문서 내용을 FieldLoadSaver 인터페이스를 구현하는 임의 유형으로 표시할 수도 있습니다. 이 유형은 구조체 포인터일 수도 있고 그렇지 않을 수도 있습니다. 검색 패키지는 문서 내용을 로드할 때 Load를 호출하고 문서 내용을 저장할 때 Save를 호출합니다. Load 및 Save 메소드는 Fields의 조각 외에 DocumentMetadata 유형도 사용하여 추가적인 문서 정보(예: 순위 또는 속성 집합)를 제공합니다. 이 인터페이스는 저장되지 않은 필드를 파생시키거나, 필드를 확인하거나, 문자열 및 HTML 필드에 특정 언어를 설정하는 일 등에 사용할 수 있습니다.

예시 코드:

type CustomFieldsExample struct {
    // Item's title and which language it is in.
    Title string
    Lang  string
    // Mass, in grams.
    Mass int
}

func (x *CustomFieldsExample) Load(fields []search.Field, meta *search.DocumentMetadata) error {
    // Load the title field, failing if any other field is found.
    for _, f := range fields {
        if f.Name != "title" {
            return fmt.Errorf("unknown field %q", f.Name)
        }
        s, ok := f.Value.(string)
        if !ok {
            return fmt.Errorf("unsupported type %T for field %q", f.Value, f.Name)
        }
        x.Title = s
        x.Lang = f.Language
    }
    // Load the mass facet, failing if any other facet is found.
    for _, f := range meta.Facets {
        if f.Name != "mass" {
            return fmt.Errorf("unknown facet %q", f.Name)
        }
        m, ok := f.Value.(float64)
        if !ok {
            return fmt.Errorf("unsupported type %T for facet %q", f.Value, f.Name)
        }
        x.Mass = int(m)
    }
    return nil
}

func (x *CustomFieldsExample) Save() ([]search.Field, *search.DocumentMetadata, error) {
    fields := []search.Field{
        {Name: "title", Value: x.Title, Language: x.Lang},
    }
    meta := &search.DocumentMetadata{
        Facets: {
            {Name: "mass", Value: float64(x.Mass)},
        },
    }
    return fields, meta, nil
}

변수

ErrInvalidDocumentType, ErrNoSuchDocument, ErrTooManyDocuments

var (
	// ErrInvalidDocumentType is returned when methods like Put, Get or Next
	// are passed a dst or src argument of invalid type.
	ErrInvalidDocumentType = errors.New("search: invalid document type")

	// ErrNoSuchDocument is returned when no document was found for a given ID.
	ErrNoSuchDocument = errors.New("search: no such document")

	// ErrTooManyDocuments is returned when the user passes too many documents to
	// PutMulti or DeleteMulti.
	ErrTooManyDocuments = fmt.Errorf("search: too many documents given to put or delete (max is %d)", maxDocumentsPerPutDelete)
)

완료

var Done = errors.New("search: query has no more results")

쿼리 반복이 완료되면 Done이 반환됩니다.

함수

func LoadStruct

func LoadStruct(dst interface{}, f []Field) error

LoadStruct는 f에서 dst로 필드를 로드합니다. dst는 구조체 포인터여야 합니다.

Atom

type Atom string

Atom은 분할할 수 없는 단일 문자열로 색인이 생성되는 내용을 포함하는 문서 필드입니다.

Cursor

type Cursor string

Cursor는 반복기의 위치를 나타냅니다.

커서의 문자열 값은 웹에 적합합니다. 나중에 사용하기 위해 저장하거나 복원할 수 있습니다.

DocumentMetadata

type DocumentMetadata struct {
	// Rank is an integer specifying the order the document will be returned in
	// search results. If zero, the rank will be set to the number of seconds since
	// 2011-01-01 00:00:00 UTC when being Put into an index.
	Rank int
	// Facets is the set of facets for this document.
	Facets []Facet
}

DocumentMetadata는 지정된 문서를 설명하는 정보를 포함하는 구조체입니다.

ErrFacetMismatch

type ErrFacetMismatch struct {
	StructType reflect.Type
	FacetName  string
	Reason     string
}

저장된 것과 다른 유형으로 속성을 로드해야 하거나 대상 구조체에서 필드가 누락되거나 내보내지지 않은 경우 ErrFacetMismatch가 반환됩니다. StructType은 Iterator.Next에 전달된 대상 인수가 가리키는 구조체의 유형입니다.

func (*ErrFacetMismatch) Error

func (e *ErrFacetMismatch) Error() string

ErrFieldMismatch

type ErrFieldMismatch struct {
	FieldName string
	Reason    string
}

저장된 것과 다른 유형으로 필드를 로드해야 하거나 대상 구조체에서 필드가 누락되거나 내보내지지 않은 경우 ErrFieldMismatch가 반환됩니다.

func (*ErrFieldMismatch) Error

func (e *ErrFieldMismatch) Error() string

패싯

type Facet struct {
	// Name is the facet name. A valid facet name matches /[A-Za-z][A-Za-z0-9_]*/.
	// A facet name cannot be longer than 500 characters.
	Name string
	// Value is the facet value.
	//
	// When being used in documents (for example, in
	// DocumentMetadata.Facets), the valid types are:
	//  - search.Atom,
	//  - float64.
	//
	// When being used in SearchOptions.Refinements or being returned
	// in FacetResult, the valid types are:
	//  - search.Atom,
	//  - search.Range.
	Value interface{}
}

Facet은 카테고리 정보를 문서에 추가하는 데 사용되는 이름/값 쌍입니다.

FacetResult

type FacetResult struct {
	Facet

	// Count is the number of times this specific facet and value appeared in the
	// matching documents.
	Count int
}

FacetResult는 검색 요청과 일치하는 문서에서 특정 속성과 값이 나오는 횟수를 나타냅니다.

FacetSearchOption

type FacetSearchOption interface {
	// contains filtered or unexported methods
}

FacetSearchOption은 검색결과에 반환되는 속성 정보를 제어합니다.

func AutoFacetDiscovery

func AutoFacetDiscovery(facetLimit, valueLimit int) FacetSearchOption

AutoFacetDiscovery는 검색에서 자동 속성 검색 기능을 사용 설정하는 FacetSearchOption을 반환합니다. 자동 속성 검색 기능은 일치하는 문서의 집계에서 가장 많이 나타나는 속성을 찾습니다.

반환되는 최대 속성 수는 facetLimit로 제어하고 속성당 최대 값 수는 facetLimit로 제어합니다. 제한이 0인 경우 기본 제한을 사용해야 함을 의미합니다.

func FacetDiscovery

func FacetDiscovery(name string, value ...interface{}) FacetSearchOption

FacetDiscovery는 검색결과와 함께 반환할 속성을 선택하는 FacetSearchOption을 반환합니다. 기본적으로 해당 속성에서 가장 자주 발생하는 값이 반환됩니다. 하지만 반환할 특정 Atom 또는 특정 범위 목록을 지정할 수도 있습니다.

func FacetDocumentDepth

func FacetDocumentDepth(depth int) FacetSearchOption

FacetDocumentDepth는 속성 결과를 준비하면서 평가할 문서 수를 제어하는 FacetSearchOption을 반환합니다.

입력란

type Field struct {
	// Name is the field name. A valid field name matches /[A-Za-z][A-Za-z0-9_]*/.
	Name string
	// Value is the field value. The valid types are:
	//  - string,
	//  - search.Atom,
	//  - search.HTML,
	//  - time.Time (stored with millisecond precision),
	//  - float64,
	//  - GeoPoint.
	Value interface{}
	// Language is a two-letter ISO 639-1 code for the field's language,
	// defaulting to "en" if nothing is specified. It may only be specified for
	// fields of type string and search.HTML.
	Language string
	// Derived marks fields that were calculated as a result of a
	// FieldExpression provided to Search. This field is ignored when saving a
	// document.
	Derived bool
}

Field는 이름/값 쌍입니다. 검색 색인의 문서는 일련의 Fields로 로드하고 저장할 수 있습니다.

func SaveStruct

func SaveStruct(src interface{}) ([]Field, error)

SaveStruct는 src의 필드를 필드 슬라이스로 반환합니다. src는 구조체 포인터여야 합니다.

FieldExpression

type FieldExpression struct {
	// Name is the name to use for the computed field.
	Name string

	// Expr is evaluated to provide a custom content snippet for each document.
	// See https://cloud.google.com/appengine/docs/standard/go/search/options for
	// the supported expression syntax.
	Expr string
}

FieldExpression은 각 결과에 대해 평가할 커스텀 표현식을 정의합니다.

FieldList

type FieldList []Field

FieldList는 FieldLoadSaver를 구현하기 위해 []Field를 변환합니다.

func (*FieldList) Load

func (l *FieldList) Load(f []Field, _ *DocumentMetadata) error

Load는 제공된 모든 필드를 l로 로드합니다. 이 함수는 먼저 *l를 빈 슬라이스로 재설정하지 않습니다.

func (*FieldList) Save

func (l *FieldList) Save() ([]Field, *DocumentMetadata, error)

Save는 l의 모든 필드를 Fields의 조각으로 반환합니다.

FieldLoadSaver

type FieldLoadSaver interface {
	Load([]Field, *DocumentMetadata) error
	Save() ([]Field, *DocumentMetadata, error)
}

추가적인 문서 메타데이터를 사용하면 FieldLoadSaver를 Fields의 조각에서 다른 항목으로 변환하거나 다른 항목에서 Fields의 조각으로 변환할 수 있습니다.

HTML

type HTML string

HTML은 해당 콘텐츠의 색인이 HTML로 생성되는 문서 필드입니다. 텍스트 노드의 색인만 생성되며 'foobar'는 'foobar'로 처리됩니다.

색인

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

Index는 문서의 색인입니다.

func Open

func Open(name string) (*Index, error)

Open은 지정된 이름의 색인을 엽니다. 해당 색인이 아직 존재하지 않으면 색인이 생성됩니다.

이 이름은 사람이 읽을 수 있는 ASCII 문자열이며, 공백 문자를 포함하거나 '!'로 시작할 수 없습니다.

func (*Index) Delete

func (x *Index) Delete(c context.Context, id string) error

Delete는 색인에서 문서를 삭제합니다.

func (*Index) DeleteMulti

func (x *Index) DeleteMulti(c context.Context, ids []string) error

DeleteMulti는 색인에서 여러 문서를 삭제합니다.

반환된 오류는 appengine.MultiError의 인스턴스일 수 있습니다. 이 경우 src와 크기가 동일하고 내부의 개별 오류가 src의 항목과 일치합니다.

func (*Index) Get

func (x *Index) Get(c context.Context, id string, dst interface{}) error

Get은 지정된 ID의 문서를 dst로 로드합니다.

이 ID는 사람이 읽을 수 있는 ASCII 문자열이며, 비어 있으면 안 되고 공백 문자를 포함하거나 '!'로 시작할 수 없습니다.

dst는 nil이 아닌 구조체 포인터이거나 FieldLoadSaver 인터페이스를 구현해야 합니다.

저장된 것과 다른 유형으로 필드를 로드해야 하거나 대상 구조체에서 필드가 누락되거나 내보내기가 되지 않았다면 ErrFieldMismatch가 반환됩니다. ErrFieldMismatch는 dst가 구조체 포인터인 경우에만 반환됩니다. 이 오류가 심각한지, 복구 가능한지, 아니면 무시 가능한지의 여부는 수신자가 결정합니다.

func (*Index) List

func (x *Index) List(c context.Context, opts *ListOptions) *Iterator

List는 색인에 있는 모든 문서를 나열합니다. 문서는 ID를 기준으로 오름차순으로 반환됩니다.

func (*Index) Put

func (x *Index) Put(c context.Context, id string, src interface{}) (string, error)

Put은 src를 색인에 저장합니다. ID가 비어 있다면 서비스에서 새 ID가 할당되어 반환됩니다. ID가 비어 있지 않다면 해당 ID의 기존 색인 항목이 대체됩니다.

이 ID는 사람이 읽을 수 있는 ASCII 문자열이며, 공백 문자를 포함하거나 '!'로 시작할 수 없습니다.

src는 nil이 아닌 구조체 포인터이거나 FieldLoadSaver 인터페이스를 구현해야 합니다.

func (*Index) PutMulti

func (x *Index) PutMulti(c context.Context, ids []string, srcs []interface{}) ([]string, error)

PutMulti는 Put과 비슷하지만 색인에 여러 문서를 한 번에 추가하는 데 더 효율적입니다.

한 번에 최대 200개의 문서를 추가할 수 있습니다. 더 추가하려고 하면 ErrTooManyDocuments가 반환됩니다.

ID는 빈 슬라이스(추가된 각 문서에 새 ID가 할당됨)이거나 src와 동일한 크기의 슬라이스가 될 수 있습니다.

오류는 appengine.MultiError의 인스턴스일 수 있습니다. 이 경우 src와 크기가 동일하고 내부의 개별 오류가 src의 항목과 일치합니다.

func (x *Index) Search(c context.Context, query string, opts *SearchOptions) *Iterator

Search는 색인에서 지정된 쿼리를 검색합니다.

반복자

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

Iterator는 색인에서 쿼리를 검색한 결과 또는 색인을 나열한 결과입니다.

func (*Iterator) Count

func (t *Iterator) Count() int

Count는 쿼리와 일치하는 문서 수의 근사치를 반환합니다. Search를 통해 반환되는 반복기에 대한 호출에만 유효합니다.

func (*Iterator) Cursor

func (t *Iterator) Cursor() Cursor

Cursor는 현재 문서, 즉 Next 호출을 통해 가장 최근에 반환된 문서에 연결된 커서를 반환합니다.

나중에 Search를 호출할 때 이 커서를 전달하면 현재 문서 다음에 오는 첫 문서부터 결과가 시작됩니다.

func (*Iterator) Facets

func (t *Iterator) Facets() ([][]FacetResult, error)

Facets는 SearchOptions에서 속성이 요청된 경우 검색결과 내에서 찾은 속성을 반환합니다.

func (*Iterator) Next

func (t *Iterator) Next(dst interface{}) (string, error)

Next는 다음 결과의 ID를 반환합니다. 더 이상 결과가 없으면 오류로 Done이 반환됩니다.

dst는 nil이 아닌 구조체 포인터이거나, FieldLoadSaver 인터페이스를 구현하거나, nil 인터페이스 값이어야 합니다. nil이 아닌 dst를 제공하면 색인 필드로 채워집니다. IDsOnly 옵션으로 이 반복기를 만들었다면 dst가 무시됩니다.

ListOptions

type ListOptions struct {
	// StartID is the inclusive lower bound for the ID of the returned
	// documents. The zero value means all documents will be returned.
	StartID string

	// Limit is the maximum number of documents to return. The zero value
	// indicates no limit.
	Limit int

	// IDsOnly indicates that only document IDs should be returned for the list
	// operation; no document fields are populated.
	IDsOnly bool
}

ListOptions는 색인에 있는 문서를 나열하는 옵션입니다. nil *ListOptions를 전달하는 것은 기본값을 사용하는 것과 같습니다.

범위

type Range struct {
	Start, End float64
}

Range는 시작(포함)부터 끝(제외)까지의 숫자 범위를 나타냅니다. 시작을 math.Inf(-1)로 지정하여 최솟값이 없음을 나타낼 수 있고 마찬가지로 끝을 math.Inf(1)로 지정할 수 있습니다. 시작 또는 끝 중 최소 하나는 유한 숫자여야 합니다.

func AtLeast

func AtLeast(min float64) Range

AtLeast는 최소값보다 크거나 같은 값과 일치하는 범위를 반환합니다.

func LessThan

func LessThan(max float64) Range

LessThan은 최대값보다 작은 값과 일치하는 범위를 반환합니다.

Scorer

type Scorer interface {
	// contains filtered or unexported methods
}

Scorer는 문서의 점수를 매기는 방법을 정의합니다.

MatchScorer, RescoringMatchScorer

var (
	// MatchScorer assigns a score based on term frequency in a document.
	MatchScorer Scorer = enumScorer{pb.ScorerSpec_MATCH_SCORER}

	// RescoringMatchScorer assigns a score based on the quality of the query
	// match. It is similar to a MatchScorer but uses a more complex scoring
	// algorithm based on match term frequency and other factors like field type.
	// Please be aware that this algorithm is continually refined and can change
	// over time without notice. This means that the ordering of search results
	// that use this scorer can also change without notice.
	RescoringMatchScorer Scorer = enumScorer{pb.ScorerSpec_RESCORING_MATCH_SCORER}
)

SearchOptions

type SearchOptions struct {
	// Limit is the maximum number of documents to return. The zero value
	// indicates no limit.
	Limit int

	// IDsOnly indicates that only document IDs should be returned for the search
	// operation; no document fields are populated.
	IDsOnly bool

	// Sort controls the ordering of search results.
	Sort *SortOptions

	// Fields specifies which document fields to include in the results. If omitted,
	// all document fields are returned. No more than 100 fields may be specified.
	Fields []string

	// Expressions specifies additional computed fields to add to each returned
	// document.
	Expressions []FieldExpression

	// Facets controls what facet information is returned for these search results.
	// If no options are specified, no facet results will be returned.
	Facets []FacetSearchOption

	// Refinements filters the returned documents by requiring them to contain facets
	// with specific values. Refinements are applied in conjunction for facets with
	// different names, and in disjunction otherwise.
	Refinements []Facet

	// Cursor causes the results to commence with the first document after
	// the document associated with the cursor.
	Cursor Cursor

	// Offset specifies the number of documents to skip over before returning results.
	// When specified, Cursor must be nil.
	Offset int

	// CountAccuracy specifies the maximum result count that can be expected to
	// be accurate. If zero, the count accuracy defaults to 20.
	CountAccuracy int
}

SearchOptions은 색인 검색 옵션입니다. nil *SearchOptions를 전달하는 것은 기본값을 사용하는 것과 같습니다.

SortExpression

type SortExpression struct {
	// Expr is evaluated to provide a sorting value for each document.
	// See https://cloud.google.com/appengine/docs/standard/go/search/options for
	// the supported expression syntax.
	Expr string

	// Reverse causes the documents to be sorted in ascending order.
	Reverse bool

	// The default value to use when no field is present or the expresion
	// cannot be calculated for a document. For text sorts, Default must
	// be of type string; for numeric sorts, float64.
	Default interface{}
}

SortExpression은 문서 정렬을 위한 단일 차원을 정의합니다.

SortOptions

type SortOptions struct {
	// Expressions is a slice of expressions representing a multi-dimensional
	// sort.
	Expressions []SortExpression

	// Scorer, when specified, will cause the documents to be scored according to
	// search term frequency.
	Scorer Scorer

	// Limit is the maximum number of objects to score and/or sort. Limit cannot
	// be more than 10,000. The zero value indicates a default limit.
	Limit int
}

SortOptions는 검색 결과의 정렬 및 점수를 제어합니다.