mirror of
https://codeberg.org/scip/esctl.git
synced 2026-08-24 08:14:18 +02:00
add doc show, enhance search, add jsonpath to search and doc show
This commit is contained in:
@@ -20,12 +20,9 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
"codeberg.org/scip/esctl/pkg/cfg"
|
||||
"github.com/elastic/go-elasticsearch/v9/typedapi/core/search"
|
||||
"github.com/elastic/go-elasticsearch/v9/typedapi/esdsl"
|
||||
"github.com/elastic/go-elasticsearch/v9/typedapi/types"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
/*
|
||||
@@ -35,40 +32,19 @@ Execute an ES search.
|
||||
additional filters can be given as -F key=value
|
||||
*/
|
||||
func Search(conf *cfg.Config, queries []string) error {
|
||||
query := esdsl.NewBoolQuery()
|
||||
search := conf.DefaultCluster.ES.Search().
|
||||
Index(conf.Index)
|
||||
|
||||
for _, q := range queries {
|
||||
parts := strings.Split(q, "=")
|
||||
if len(parts) != 2 {
|
||||
return fmt.Errorf("search queries must be in the form field=pattern")
|
||||
if len(queries) > 0 {
|
||||
req, err := prepareQuery(conf, queries)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
query.Must(esdsl.NewMatchQuery(parts[0], parts[1]))
|
||||
search.Request(req)
|
||||
}
|
||||
|
||||
filters := make([]types.QueryVariant, len(conf.Filter))
|
||||
|
||||
for idx, filter := range conf.Filter {
|
||||
parts := strings.Split(filter, "=")
|
||||
if len(parts) != 2 {
|
||||
return fmt.Errorf("invalid filter spec: %s, expecting key=value", filter)
|
||||
}
|
||||
|
||||
filters[idx] = esdsl.NewTermQuery(parts[0], esdsl.NewFieldValue().String(parts[1]))
|
||||
}
|
||||
|
||||
if len(filters) > 0 {
|
||||
query.Filter(filters...)
|
||||
}
|
||||
|
||||
res, err := conf.DefaultCluster.ES.Search().
|
||||
Index(conf.Index).
|
||||
Request(&search.Request{
|
||||
Query: query.QueryCaster(),
|
||||
From: &conf.From,
|
||||
Size: &conf.To,
|
||||
}).
|
||||
Do(context.Background())
|
||||
res, err := search.Do(context.Background())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to run search (esdsl): %s", err)
|
||||
}
|
||||
@@ -76,7 +52,18 @@ func Search(conf *cfg.Config, queries []string) error {
|
||||
slog.Debug("ES result", "search", res)
|
||||
|
||||
for _, hit := range res.Hits.Hits {
|
||||
fmt.Printf("%s\n", hit.Source_)
|
||||
docjson := fmt.Sprintf(`{"id":%s, "score":%0.4f, "index":"%s", "source":%s}`,
|
||||
*hit.Id_,
|
||||
*hit.Score_,
|
||||
hit.Index_,
|
||||
hit.Source_)
|
||||
|
||||
if conf.Path != "" {
|
||||
value := gjson.Get(docjson, conf.Path)
|
||||
fmt.Println(value.String())
|
||||
} else {
|
||||
fmt.Println(docjson)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
Reference in New Issue
Block a user