Files
esctl/pkg/es/search.go

71 lines
1.6 KiB
Go
Raw Normal View History

2026-04-21 10:50:09 +02:00
/*
Copyright © 2026 Thomas von Dein
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package es
import (
"context"
"fmt"
"log/slog"
2026-04-21 10:50:09 +02:00
"codeberg.org/scip/esctl/pkg/cfg"
"github.com/tidwall/gjson"
2026-04-21 10:50:09 +02:00
)
/*
Execute an ES search.
q is the actual search query given as arg to the 'search' cmd
additional filters can be given as -F key=value
*/
func Search(conf *cfg.Config, queries []string) error {
search := conf.DefaultCluster.ES.Search().
Index(conf.Index)
if len(queries) > 0 {
req, err := prepareQuery(conf, queries)
if err != nil {
return err
}
search.Request(req)
}
2026-04-21 10:50:09 +02:00
res, err := search.Do(context.Background())
2026-04-21 10:50:09 +02:00
if err != nil {
return fmt.Errorf("failed to run search (esdsl): %s", err)
2026-04-21 10:50:09 +02:00
}
slog.Debug("ES result", "search", res)
2026-04-21 10:50:09 +02:00
for _, hit := range res.Hits.Hits {
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)
}
2026-04-21 10:50:09 +02:00
}
return nil
}