Categorygithub.com/aliworkshop/esquery
modulepackage
0.4.1
Repository: https://github.com/aliworkshop/esquery.git
Documentation: pkg.go.dev

# README

esquery

Build Status

A non-obtrusive, idiomatic and easy-to-use query and aggregation builder for the official Go client for ElasticSearch.

Table of Contents

Description

esquery alleviates the need to use extremely nested maps (map[string]interface{}) and serializing queries to JSON manually. It also helps eliminating common mistakes such as misspelling query types, as everything is statically typed.

Using esquery can make your code much easier to write, read and maintain, and significantly reduce the amount of code you write. Wanna know how much code you'll save? just check this project's tests.

Status

This is an early release, API may still change.

Installation

esquery is a Go module. To install, simply run this in your project's root directory:

go get github.com/aliworkshop/esquery

Usage

esquery provides a method chaining-style API for building and executing queries and aggregations. It does not wrap the official Go client nor does it require you to change your existing code in order to integrate the library. Queries can be directly built with esquery, and executed by passing an *elasticsearch.Client instance (with optional search parameters). Results are returned as-is from the official client (e.g. *esapi.Response objects).

Getting started is extremely simple:

package main

import (
	"context"
	"log"

	"github.com/aliworkshop/esquery"
	"github.com/elastic/go-elasticsearch/v8"
)

func main() {
    // connect to an ElasticSearch instance
    es, err := elasticsearch.NewDefaultClient()
    if err != nil {
        log.Fatalf("Failed creating client: %s", err)
    }

    // run a boolean search query
    res, err := esquery.Search().
        Query(
            esquery.
                Bool().
                Must(esquery.Term("title", "Go and Stuff")).
                Filter(esquery.Term("tag", "tech")),
        ).
        Aggs(
            esquery.Avg("average_score", "score"),
            esquery.Max("max_score", "score"),
        ).
        Size(20).
        Run(
            es,
            es.Search.WithContext(context.TODO()),
            es.Search.WithIndex("test"),
        )
        if err != nil {
            log.Fatalf("Failed searching for stuff: %s", err)
        }

    defer res.Body.Close()

    // ...
}

Notes

  • esquery currently supports version 7 of the ElasticSearch Go client.
  • The library cannot currently generate "short queries". For example, whereas ElasticSearch can accept this:
{ "query": { "term": { "user": "Kimchy" } } }

The library will always generate this:

{ "query": { "term": { "user": { "value": "Kimchy" } } } }

This is also true for queries such as "bool", where fields like "must" can either receive one query object, or an array of query objects. esquery will generate an array even if there's only one query object.

Features

Supported Queries

The following queries are currently supported:

ElasticSearch DSLesquery Function
"match"Match()
"match_bool_prefix"MatchBoolPrefix()
"match_phrase"MatchPhrase()
"match_phrase_prefix"MatchPhrasePrefix()
"match_all"MatchAll()
"match_none"MatchNone()
"multi_match"MultiMatch()
"exists"Exists()
"fuzzy"Fuzzy()
"ids"IDs()
"prefix"Prefix()
"range"Range()
"regexp"Regexp()
"term"Term()
"terms"Terms()
"terms_set"TermsSet()
"wildcard"Wildcard()
"bool"Bool()
"boosting"Boosting()
"constant_score"ConstantScore()
"dis_max"DisMax()

Supported Aggregations

The following aggregations are currently supported:

ElasticSearch DSLesquery Function
"avg"Avg()
"weighted_avg"WeightedAvg()
"cardinality"Cardinality()
"max"Max()
"min"Min()
"sum"Sum()
"value_count"ValueCount()
"percentiles"Percentiles()
"stats"Stats()
"string_stats"StringStats()
"top_hits"TopHits()
"terms"TermsAgg()

Supported Top Level Options

The following top level options are currently supported:

ElasticSearch DSLesquery.Search Function
"highlight"Highlight()
"explain"Explain()
"from"From()
"postFilter"PostFilter()
"query"Query()
"aggs"Aggs()
"size"Size()
"sort"Sort()
"source"SourceIncludes(), SourceExcludes()
"timeout"Timeout()

Custom Queries and Aggregations

To execute an arbitrary query or aggregation (including those not yet supported by the library), use the CustomQuery() or CustomAgg() functions, respectively. Both accept any map[string]interface{} value.

License

This library is distributed under the terms of the Apache License 2.0.

# Functions

Aggregate is a shortcut for creating a SearchRequest with aggregations.
Avg creates an aggregation of type "avg", with the provided name and on the provided field.
Bool creates a new compound query of type "bool".
Boosting creates a new compound query of type "boosting".
Cardinality creates a new aggregation of type "cardinality" with the provided name and on the provided field.
ConstantScore creates a new query of type "contant_score" with the provided filter query.
Count creates a new count request with the provided query.
CustomAgg generates a custom aggregation from an arbitrary map provided by the user.
CustomQuery generates a custom request of type "query" from an arbitrary map provided by the user.
Delete creates a new DeleteRequest object, to be filled via method chaining.
DisMax creates a new compound query of type "dis_max" with the provided queries.
Exists creates a new query of type "exists" on the provided field.
Filter creates a new aggregation of type "filter".
Fuzzy creates a new query of type "fuzzy" on the provided field and using the provided value.
Highlight creates a new "query" of type "highlight".
IDs creates a new query of type "ids" with the provided values.
Match creates a new query of type "match" with the provided field name.
MatchAll creates a new query of type "match_all".
MatchBoolPrefix creates a new query of type "match_bool_prefix" with the provided field name.
MatchNone creates a new query of type "match_none".
MatchPhrase creates a new query of type "match_phrase" with the provided field name.
MatchPhrasePrefix creates a new query of type "match_phrase_prefix" with the provided field name.
Max creates a new aggregation of type "max", with the provided name and on the provided field.
Min creates a new aggregation of type "min", with the provided name and on the provided field.
MultiMatch creates a new query of type "multi_match".
NestedAgg creates a new aggregation of type "nested".
Percentiles creates a new aggregation of type "percentiles" with the provided name and on the provided field.
Prefix creates a new query of type "prefix", on the provided field and using the provided prefix value.
Query is a shortcut for creating a SearchRequest with only a query.
Range creates a new query of type "range" on the provided field.
Regexp creates a new query of type "regexp" on the provided field and using the provided regular expression.
Search creates a new SearchRequest object, to be filled via method chaining.
Stats creates a new "stats" aggregation with the provided name and on the provided field.
StringStats creates a new "string_stats" aggregation with the provided name and on the provided field.
Sum creates a new aggregation of type "sum", with the provided name and on the provided field.
Term creates a new query of type "term" on the provided field and using the provide value.
Terms creates a new query of type "terms" on the provided field, and optionally with the provided term values.
TermsAgg creates a new aggregation of type "terms".
TermsSet creates a new query of type "terms_set" on the provided field and optionally using the provided terms.
TopHits creates an aggregation of type "top_hits".
ValueCount creates a new aggregation of type "value_count", with the provided name and on the provided field.
WeightedAvg creates a new aggregation of type "weighted_agg" with the provided name.
Wildcard creates a new query of type "wildcard" on the provided field and using the provided regular expression value.

# Constants

BoundaryScannerChars is the "chars" value.
No description provided by the author
BoundaryScannerSentence is the "sentence" value.
BoundaryScannerWord is the "word" value.
EncoderDefault is the "default" value.
EncoderHtml is the "html" value.
FragmenterSimple is the "simple" value.
FragmentSpan is the "span" value.
HighlighterFvh is the "fvh" value.
HighlighterPlain is the "plain" value.
HighlighterUnified is the "unified" value.
TypeBestFields is the "best_fields" type.
TypeMostFields is the "bool_prefix" type.
TypeMostFields is the "cross_fields" type.
TypeMostFields is the "most_fields" type.
TypeMostFields is the "phrase" type.
TypeMostFields is the "phrase_prefix" type.
OperatorAnd is the "and" operator.
OperatorOr is the "or" operator.
OrderAsc represents sorting in ascending order.
OrderDesc represents sorting in descending order.
OrderNone is the "none" value.
OrderScore is the "score" value.
RangeContains is the "CONTAINS" relation.
RangeIntersects is the "INTERSECTS" relation.
RangeWithin is the "WITHIN" relation.
No description provided by the author
TagsSchemaStyled is the "styled" value.
TypeMatch denotes a query of type "match".
TypeMatchBool denotes a query of type "match_bool_prefix".
TypeMatchPhrase denotes a query of type "match_phrase".
TypeMatchPhrasePrefix denotes a query of type "match_phrase_prefix".
ZeroTermsAll is the "all" value.
ZeroTermsNone is the "none" value.

# Structs

AvgAgg represents an aggregation of type "avg", as described in https://www.elastic.co/guide/en/elasticsearch/reference/ current/search-aggregations-metrics-avg-aggregation.html.
BaseAgg contains several fields that are common for all aggregation types.
BaseAggParams contains fields that are common to most metric-aggregation types.
BoolQuery represents a compound query of type "bool", as described in https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html.
BoostingQuery represents a compound query of type "boosting", as described in https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-boosting-query.html.
CardinalityAgg represents an aggregation of type "cardinality", as described in https://www.elastic.co/guide/en/elasticsearch/reference/ current/search-aggregations-metrics-cardinality-aggregation.html.
ConstantScoreQuery represents a compound query of type "constant_score", as described in https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-constant-score-query.html.
CountRequest represents a request to get the number of matches for a search query, as described in: https://www.elastic.co/guide/en/elasticsearch/reference/current/search-count.html.
CustomAggMap represents an arbitrary aggregation map for custom aggregations.
DeleteRequest represents a request to ElasticSearch's Delete By Query API, described in https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete-by-query.html.
DisMaxQuery represents a compound query of type "dis_max", as described in https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-dis-max-query.html.
ExistsQuery represents a query of type "exists", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-exists-query.html.
No description provided by the author
FuzzyQuery represents a query of type "fuzzy", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-fuzzy-query.html.
IDsQuery represents a query of type "ids", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-ids-query.html.
MatchAllQuery represents a query of type "match_all" or "match_none", as described in https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-all-query.html.
MatchQuery represents a query of type "match", "match_bool_prefix", "match_phrase" and "match_phrase_prefix".
MaxAgg represents an aggregation of type "max", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/ current/search-aggregations-metrics-max-aggregation.html.
MinAgg represents an aggregation of type "min", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/ current/search-aggregations-metrics-min-aggregation.html.
No description provided by the author
No description provided by the author
PercentilesAgg represents an aggregation of type "percentiles", as described in https://www.elastic.co/guide/en/elasticsearch/reference/ current/search-aggregations-metrics-percentile-aggregation.html.
PrefixQuery represents query of type "prefix", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-prefix-query.html.
No description provided by the author
RangeQuery represents a query of type "range", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-range-query.html.
RegexpQuery represents a query of type "regexp", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-regexp-query.html.
SearchRequest represents a request to ElasticSearch's Search API, described in https://www.elastic.co/guide/en/elasticsearch/reference/current/search.html.
Source represents the "_source" option which is commonly accepted in ES queries.
StatsAgg represents an aggregation of type "stats", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/ current/search-aggregations-metrics-stats-aggregation.html.
StringStatsAgg represents an aggregation of type "string_stats", as described in https://www.elastic.co/guide/en/elasticsearch/reference/ current/search-aggregations-metrics-string-stats-aggregation.html.
SumAgg represents an aggregation of type "sum", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/ current/search-aggregations-metrics-sum-aggregation.html.
TermQuery represents a query of type "term", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-term-query.html.
TermsAggregation represents an aggregation of type "terms", as described in https://www.elastic.co/guide/en/elasticsearch/reference/current/ search-aggregations-bucket-terms-aggregation.html.
TermsQuery represents a query of type "terms", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-query.html.
TermsSetQuery represents a query of type "terms_set", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-set-query.html.
TopHitsAgg represents an aggregation of type "top_hits", as described in https://www.elastic.co/guide/en/elasticsearch/reference/ current/search-aggregations-metrics-top-hits-aggregation.html.
ValueCountAgg represents an aggregation of type "value_count", as described in https://www.elastic.co/guide/en/elasticsearch/reference/ current/search-aggregations-metrics-valuecount-aggregation.html.
WeightedAvgAgg represents an aggregation of type "weighted_avg", as described in https://www.elastic.co/guide/en/elasticsearch/reference/ current/search-aggregations-metrics-weight-avg-aggregation.html.

# Interfaces

Aggregation is an interface that each aggregation type must implement.
Mappable is the interface implemented by the various query and aggregation types provided by the package.

# Type aliases

CustomQueryMap represents an arbitrary query map for custom queries.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
MatchOperator is an enumeration type representing supported values for a match query's "operator" parameter.
MatchType is an enumeration type representing supported values for a multi match query's "type" parameter.
Order is the ordering for a sort key (ascending, descending).
RangeRelation is an enumeration type for a range query's "relation" field.
Sort represents a list of keys to sort by.
ZeroTerms is an enumeration type representing supported values for a match query's "zero_terms_query" parameter.