From 7d266589b770f1d780ecd628dec705e658d9c1c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=B6ksel=20K=C3=BC=C3=A7=C3=BCk=C5=9Fahin?= Date: Wed, 15 Jan 2025 00:16:33 +0300 Subject: [PATCH] web: remove library files on web branch --- Makefile | 18 - benchmarks/run_bench.go | 357 ----------- benchmarks/tests/aggs_benchmark_test.go | 149 ----- benchmarks/tests/complex_benchmark_test.go | 166 ----- .../tests/conditional_benchmark_test.go | 135 ----- .../tests/intermediate_benchmark_test.go | 107 ---- benchmarks/tests/marshal/marshal_string.go | 14 - benchmarks/tests/mixed_benchmark_test.go | 122 ---- benchmarks/tests/nested_benchmark_test.go | 83 --- benchmarks/tests/simple_benchmark_test.go | 60 -- benchmarks/tests/ty_example_benchmark_test.go | 83 --- es/aggregations.go | 388 ------------ es/aggregations_test.go | 432 ------------- es/base_query.go | 297 --------- es/base_query_test.go | 399 ------------ es/bool_query.go | 241 -------- es/bool_query_test.go | 320 ---------- es/condition/if.go | 25 - es/condition/if_test.go | 61 -- es/enums/match/operator/operator.go | 32 - es/enums/match/operator/operator_test.go | 25 - .../zero-terms-query/zero_terms_query.go | 33 - .../zero-terms-query/zero_terms_query_test.go | 25 - es/enums/nested/score-mode/score_mode.go | 42 -- es/enums/nested/score-mode/score_mode_test.go | 27 - es/enums/sort/mode/mode.go | 45 -- es/enums/sort/mode/mode_test.go | 29 - es/enums/sort/order/order.go | 34 -- es/enums/sort/order/order_test.go | 26 - es/exists_query.go | 80 --- es/exists_query_test.go | 164 ----- es/match_all_query.go | 50 -- es/match_all_query_test.go | 37 -- es/match_none_query.go | 87 --- es/match_none_query_test.go | 41 -- es/match_query.go | 281 --------- es/match_query_test.go | 282 --------- es/nested_query.go | 82 --- es/nested_query_test.go | 80 --- es/query_string.go | 567 ------------------ es/query_string_test.go | 325 ---------- es/range.go | 174 ------ es/range_test.go | 173 ------ es/regexp_query.go | 108 ---- es/regexp_query_test.go | 88 --- es/simple_query_string.go | 308 ---------- es/simple_query_string_test.go | 216 ------- es/term_query.go | 141 ----- es/term_query_test.go | 206 ------- es/terms_query.go | 143 ----- es/terms_query_test.go | 211 ------- es/types.go | 21 - example/example.go | 104 ---- go.mod | 5 - internal/testing/constants/constants.go | 8 - internal/testing/container/elasticsearch.go | 84 --- internal/testing/elasticsearch_repository.go | 175 ------ internal/testing/go.mod | 64 -- internal/testing/go.sum | 197 ------ internal/testing/query_string_test.go | 46 -- internal/testing/regexp_query_test.go | 51 -- internal/testing/search_response.go | 18 - internal/testing/simple_query_string_test.go | 46 -- internal/testing/suite_test.go | 93 --- internal/testing/term_query_test.go | 41 -- internal/testing/terms_query_test.go | 47 -- test/assert/assert.go | 96 --- 67 files changed, 8715 deletions(-) delete mode 100644 Makefile delete mode 100644 benchmarks/run_bench.go delete mode 100644 benchmarks/tests/aggs_benchmark_test.go delete mode 100644 benchmarks/tests/complex_benchmark_test.go delete mode 100644 benchmarks/tests/conditional_benchmark_test.go delete mode 100644 benchmarks/tests/intermediate_benchmark_test.go delete mode 100644 benchmarks/tests/marshal/marshal_string.go delete mode 100644 benchmarks/tests/mixed_benchmark_test.go delete mode 100644 benchmarks/tests/nested_benchmark_test.go delete mode 100644 benchmarks/tests/simple_benchmark_test.go delete mode 100644 benchmarks/tests/ty_example_benchmark_test.go delete mode 100644 es/aggregations.go delete mode 100644 es/aggregations_test.go delete mode 100644 es/base_query.go delete mode 100644 es/base_query_test.go delete mode 100644 es/bool_query.go delete mode 100644 es/bool_query_test.go delete mode 100644 es/condition/if.go delete mode 100644 es/condition/if_test.go delete mode 100644 es/enums/match/operator/operator.go delete mode 100644 es/enums/match/operator/operator_test.go delete mode 100644 es/enums/match/zero-terms-query/zero_terms_query.go delete mode 100644 es/enums/match/zero-terms-query/zero_terms_query_test.go delete mode 100644 es/enums/nested/score-mode/score_mode.go delete mode 100644 es/enums/nested/score-mode/score_mode_test.go delete mode 100644 es/enums/sort/mode/mode.go delete mode 100644 es/enums/sort/mode/mode_test.go delete mode 100644 es/enums/sort/order/order.go delete mode 100644 es/enums/sort/order/order_test.go delete mode 100644 es/exists_query.go delete mode 100644 es/exists_query_test.go delete mode 100644 es/match_all_query.go delete mode 100644 es/match_all_query_test.go delete mode 100644 es/match_none_query.go delete mode 100644 es/match_none_query_test.go delete mode 100644 es/match_query.go delete mode 100644 es/match_query_test.go delete mode 100644 es/nested_query.go delete mode 100644 es/nested_query_test.go delete mode 100644 es/query_string.go delete mode 100644 es/query_string_test.go delete mode 100644 es/range.go delete mode 100644 es/range_test.go delete mode 100644 es/regexp_query.go delete mode 100644 es/regexp_query_test.go delete mode 100644 es/simple_query_string.go delete mode 100644 es/simple_query_string_test.go delete mode 100644 es/term_query.go delete mode 100644 es/term_query_test.go delete mode 100644 es/terms_query.go delete mode 100644 es/terms_query_test.go delete mode 100644 es/types.go delete mode 100644 example/example.go delete mode 100644 go.mod delete mode 100644 internal/testing/constants/constants.go delete mode 100644 internal/testing/container/elasticsearch.go delete mode 100644 internal/testing/elasticsearch_repository.go delete mode 100644 internal/testing/go.mod delete mode 100644 internal/testing/go.sum delete mode 100644 internal/testing/query_string_test.go delete mode 100644 internal/testing/regexp_query_test.go delete mode 100644 internal/testing/search_response.go delete mode 100644 internal/testing/simple_query_string_test.go delete mode 100644 internal/testing/suite_test.go delete mode 100644 internal/testing/term_query_test.go delete mode 100644 internal/testing/terms_query_test.go delete mode 100644 test/assert/assert.go diff --git a/Makefile b/Makefile deleted file mode 100644 index cafd148..0000000 --- a/Makefile +++ /dev/null @@ -1,18 +0,0 @@ -EXISTING_VERSION := $(shell git describe --abbrev=0 --tags) -NEW_VERSION := $(shell echo $(EXISTING_VERSION) | awk -F. '{print ""$$1"."$$2"."$$3 + 1}') - -tag_and_push: - git tag $(NEW_VERSION) - git push origin $(NEW_VERSION) - -run-test: - go test ./es/... -v -race -coverprofile=coverage.txt -covermode=atomic - -linter: - golangci-lint run -c .golangci.yml --timeout=5m -v --fix - -unit-test-pretty: - go test ./... -count=1 -v -json | gotestfmt - -run-benchmark: - go run ./benchmarks/run_bench.go -cooldown=15 -save=csv \ No newline at end of file diff --git a/benchmarks/run_bench.go b/benchmarks/run_bench.go deleted file mode 100644 index bffadcb..0000000 --- a/benchmarks/run_bench.go +++ /dev/null @@ -1,357 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "os" - "os/exec" - "path/filepath" - "regexp" - "strconv" - "strings" - "time" -) - -const helpMessage = ` -Usage: run_bench [OPTIONS] - -Options: - -help Show this help message and exit. - - -cooldown=value Set the cooldown period. Valid values: - - "disabled" or "0" to disable cooldown. - - An integer between 1 and 300 (inclusive). - Default: 20 seconds. - - -benchtime=value Set the benchmark time duration. Valid value: - - An integer between 1 and 30 (inclusive). - Default: 5 seconds. - - -save=value Specify the format to save benchmark results. Valid values: - - "json" to save as JSON format. - - "csv" to save as CSV format. - Default: json. - - -wd=value, Set the working directory. Valid value: - -workingdirectory=value - An absolute path to a directory that exists. - Default: project working directory. - -Example: - go run run_bench.go -cooldown=10 -benchtime=5 -save=csv -wd=/absolute/path/to/directory - - or - - go run run_bench.go (it will run with default settings)` - -type Run struct { - Name string `json:"name"` - Score float64 `json:"score"` - NsPerOp float64 `json:"nsop"` -} - -type BenchmarkResult struct { - Os string `json:"os"` - Arch string `json:"arch"` - Runs []Run `json:"runs"` - RunTime float64 `json:"runTime"` -} - -type Parameters struct { - CooldownFunc func() - SaveFunc func([]*BenchmarkResult, string) error - WorkingDirectory string - Benchtime uint -} - -func parseBenchmarkOutput(benchmarkOutput string) (*BenchmarkResult, error) { - benchmarkRegex := regexp.MustCompile(`goos:\s+(\w+)\ngoarch:\s+([\w]+)(.*\n)+PASS\nok\s*[a-z \-]+\s*(\d+(\.\d+)?)s`) - matches := benchmarkRegex.FindStringSubmatch(benchmarkOutput) - goos, goarch, runTime := "", "", 0.0 - if len(matches) > 0 { - goos = matches[1] - goarch = matches[2] - runTimeSeconds, err := strconv.ParseFloat(matches[4], 64) - if err != nil { - return nil, err - } - runTime = runTimeSeconds - } - - benchmarkRunRegex := regexp.MustCompile(`^(Benchmark\w+)-\d+\s+(\d+(\.\d+)?)\s+(\d+(\.\d+)?) ns/op`) - lines := strings.Split(benchmarkOutput, "\n") - runs := make([]Run, 0) - for _, line := range lines { - matches = benchmarkRunRegex.FindStringSubmatch(line) - if len(matches) > 0 { - score, err := strconv.ParseFloat(matches[2], 64) - if err != nil { - return nil, err - } - nsPerOp, err := strconv.ParseFloat(matches[4], 64) - if err != nil { - return nil, err - } - runs = append(runs, Run{ - Name: matches[1], - Score: score, - NsPerOp: nsPerOp, - }) - } - } - - return &BenchmarkResult{ - Os: goos, - Arch: goarch, - Runs: runs, - RunTime: runTime, - }, nil -} - -func generateCommand(projectDirectory, testFilePath string, benchtimeAmount uint) *exec.Cmd { - benchtime := fmt.Sprintf("-benchtime=%ds", benchtimeAmount) - cmd := exec.Command("go", "test", "-bench=.", benchtime, testFilePath) - cmd.Dir = projectDirectory - return cmd -} - -func runCommand(cmd *exec.Cmd) (*BenchmarkResult, error) { - output, err := cmd.CombinedOutput() - if err != nil { - return nil, fmt.Errorf("#combinedOutput - output: %s, err: %w", string(output), err) - } - return parseBenchmarkOutput(string(output)) -} - -func findBenchmarkTestFiles(projectDirectory string) ([]string, error) { - var benchmarkFiles []string - if err := filepath.Walk(projectDirectory, func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - if !info.IsDir() && filepath.Ext(path) == ".go" { - if matched, _ := filepath.Match("*_benchmark_test.go", info.Name()); matched { - relativePath, _ := filepath.Rel(projectDirectory, path) - benchmarkFiles = append(benchmarkFiles, relativePath) - } - } - return nil - }); err != nil { - return nil, err - } - return benchmarkFiles, nil -} - -func saveResultsAsJSON(results []*BenchmarkResult, fileName string) error { - fileName = fmt.Sprintf("%s.json", fileName) - file, err := os.Create(fileName) - if err != nil { - return fmt.Errorf("failed to create file %s: %w", fileName, err) - } - defer file.Close() - - encoder := json.NewEncoder(file) - if err = encoder.Encode(results); err != nil { - return fmt.Errorf("failed to encode results to JSON: %w", err) - } - return nil -} - -func saveResultsAsCSV(results []*BenchmarkResult, fileName string) error { - fileName = fmt.Sprintf("%s.csv", fileName) - file, err := os.Create(fileName) - if err != nil { - return fmt.Errorf("failed to create file %s: %w", fileName, err) - } - defer file.Close() - - var sb strings.Builder - sb.WriteString("Name;Score;ns/op\n") - for _, result := range results { - for _, run := range result.Runs { - fmt.Fprintf(&sb, "%s;%.1f;%.1f\n", run.Name, run.Score, run.NsPerOp) - } - } - _, err = file.WriteString(sb.String()) - if err != nil { - return fmt.Errorf("failed to write results to CSV: %w", err) - } - return nil -} - -func formatTimeAsFileName(t time.Time) string { - return t.Format("2006-01-02_15-04-05") -} - -func formatTimeAsStamp(t time.Time) string { - return t.Format("2006-01-02 15:04:05") -} - -func runBenchmarkSuite(parameters Parameters) error { - projectDirectory := parameters.WorkingDirectory - benchmarkTestFiles, err := findBenchmarkTestFiles(projectDirectory) - if err != nil { - return fmt.Errorf("could not find benchmark test files: %w", err) - } - results := make([]*BenchmarkResult, 0) - startTime := time.Now() - fmt.Printf("-- Starting Benchmark Suite at %s\n", formatTimeAsStamp(startTime)) - for _, testFile := range benchmarkTestFiles { - fmt.Printf("%s Running benchmark for %s\n", formatTimeAsStamp(time.Now()), testFile) - cmd := generateCommand(projectDirectory, testFile, parameters.Benchtime) - result, err := runCommand(cmd) - if err != nil { - fmt.Printf("Error! Failed to run benchmark for %s. err: %s", testFile, err.Error()) - } - results = append(results, result) - parameters.CooldownFunc() - } - endTime := time.Now() - elapsedTime := endTime.Sub(startTime) - fmt.Printf("-- Benchmark Suite completed at %s\n", formatTimeAsStamp(endTime)) - fmt.Printf("-- Benchmarks ran for %.2fs\n", elapsedTime.Seconds()) - resultFileName := fmt.Sprintf("benchmark_results_%s", formatTimeAsFileName(startTime)) - if err = parameters.SaveFunc(results, resultFileName); err != nil { - return fmt.Errorf("could not save benchmark results to file %s: %w", resultFileName, err) - } - return nil -} - -func printHelpAndExit() { - fmt.Println(helpMessage) - os.Exit(0) -} - -func isHelp(arg string) bool { - arg = strings.ToLower(arg) - return arg == "help" || arg == "-help" || arg == "--help" -} - -func cooldownArg(value string) (func(), error) { - switch value { - case "disabled", "0": - return func() {}, nil - } - cooldownAmount, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return nil, fmt.Errorf("illegal value for -cooldown parameter") - } - if cooldownAmount < 1 { - return nil, fmt.Errorf("cooldown could not be a negative number") - } - if cooldownAmount > 300 { - return nil, fmt.Errorf("cooldown could not be greater than 300") - } - return func() { - time.Sleep(time.Duration(cooldownAmount) * time.Second) - }, nil -} - -func benchtimeArg(value string) (uint, error) { - benchtime, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return 0, fmt.Errorf("illegal value for -benchtime parameter") - } - if benchtime < 1 { - return 0, fmt.Errorf("benchtime must be a possitive number") - } - if benchtime > 30 { - return 0, fmt.Errorf("benchtime could not be greater than 30") - } - return uint(benchtime), nil -} - -func saveArg(value string) (func([]*BenchmarkResult, string) error, error) { - switch value { - case "json": - return saveResultsAsJSON, nil - case "csv": - return saveResultsAsCSV, nil - } - return nil, fmt.Errorf("illegal value for -save parameter") -} - -func workingDirectoryArg(path string) (string, error) { - info, err := os.Stat(path) - if os.IsNotExist(err) { - return "", fmt.Errorf("%s does not exists on the system", path) - } - if err != nil { - return "", err - } - if !info.IsDir() { - return "", fmt.Errorf("%s not a directory path", path) - } - if !filepath.IsAbs(path) { - return "", fmt.Errorf("path must be absolute and start with /") - } - return path, nil -} - -func ensureResult[T any](result T, err error) T { - if err != nil { - fmt.Printf("Error: %s\n", err.Error()) - printHelpAndExit() - } - return result -} - -func normalizeString(text string) string { - return strings.ToLower(strings.TrimSpace(text)) -} - -func parseParameters(args []string) Parameters { - projectDirectory, err := os.Getwd() - if err != nil { - panic(fmt.Errorf("could not read project directory: %w", err)) - } - parameters := Parameters{ - CooldownFunc: func() { time.Sleep(20 * time.Second) }, - Benchtime: 5, - SaveFunc: saveResultsAsJSON, - WorkingDirectory: projectDirectory, - } - for _, arg := range args { - if isHelp(arg) { - printHelpAndExit() - } - // arg format: -key=value - if arg[0] != '-' { - fmt.Printf("Error: All arguments must start with a single hyphen (-)\n") - printHelpAndExit() - } - keyValue := strings.Split(arg[1:], "=") - if len(keyValue) != 2 { - fmt.Printf("Error: Arguments must be in the format -key=value\n") - printHelpAndExit() - } - key, value := normalizeString(keyValue[0]), normalizeString(keyValue[1]) - switch key { - case "cooldown": - parameters.CooldownFunc = ensureResult(cooldownArg(value)) - case "benchtime": - parameters.Benchtime = ensureResult(benchtimeArg(value)) - case "save": - parameters.SaveFunc = ensureResult(saveArg(value)) - case "wd", "workingdirectory": - parameters.WorkingDirectory = ensureResult(workingDirectoryArg(value)) - default: - fmt.Printf("Error: unknown parameter <%s>. please read the help message 🙏\n", key) - printHelpAndExit() - } - // fmt.Printf("[DEBUG] key: %s, value: %s\n", key, value) - } - return parameters -} - -func main() { - // -help - // -cooldown = disable, number[1,300] default 20 - // -benchtime = number[1, 30] default 5 - // -save = json, csv default json - // -wd, -workingdirectory = string directory default project working directory later - - parameters := parseParameters(os.Args[1:]) - if err := runBenchmarkSuite(parameters); err != nil { - panic(err) - } -} diff --git a/benchmarks/tests/aggs_benchmark_test.go b/benchmarks/tests/aggs_benchmark_test.go deleted file mode 100644 index 9e90137..0000000 --- a/benchmarks/tests/aggs_benchmark_test.go +++ /dev/null @@ -1,149 +0,0 @@ -package tests_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/benchmarks/tests/marshal" - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/es/enums/sort/order" - "github.com/Trendyol/es-query-builder/test/assert" -) - -func createAggsQuery() map[string]any { - query := es.NewQuery( - es.Bool(). - Must( - es.Term("type", "File"), - es.Range("indexedAt"). - GreaterThan("2020-06-01"). - LesserThanOrEqual("now"), - ). - MustNot( - es.Exists("file.name"), - )). - Size(5_000). - Sort( - es.Sort("modifiedDate").Order(order.Desc), - es.Sort("indexedAt").Order(order.Asc), - ). - Aggs("by_category", es.AggTerms(). - Field("category.keyword"). - Size(250). - Aggs("nested_reviews", es.AggNested(). - Path("reviews"). - Aggs("average_rating", es.AggAvg(). - Field("reviews.rating"), - ). - Aggs("by_reviewer", es.AggTerms(). - Field("reviews.reviewer.keyword"). - Aggs("max_reviewer_rating", es.AggMax(). - Field("reviews.rating"), - ), - ), - ), - ) - return query -} - -func createAggsQueryVanilla() map[string]any { - query := map[string]interface{}{ - "size": 5000, - "sort": []map[string]interface{}{ - { - "modifiedDate": map[string]interface{}{ - "order": "desc", - }, - }, - { - "indexedAt": map[string]interface{}{ - "order": "asc", - }, - }, - }, - "query": map[string]interface{}{ - "bool": map[string]interface{}{ - "must": []map[string]interface{}{ - { - "term": map[string]interface{}{ - "type": map[string]interface{}{ - "value": "File", - }, - }, - }, - { - "range": map[string]interface{}{ - "indexedAt": map[string]interface{}{ - "gt": "2020-06-01", - "lte": "now", - }, - }, - }, - }, - "must_not": []map[string]interface{}{ - { - "exists": map[string]interface{}{ - "field": "file.name", - }, - }, - }, - }, - }, - "aggs": map[string]interface{}{ - "by_category": map[string]interface{}{ - "terms": map[string]interface{}{ - "field": "category.keyword", - "size": 250, - }, - "aggs": map[string]interface{}{ - "nested_reviews": map[string]interface{}{ - "nested": map[string]interface{}{ - "path": "reviews", - }, - "aggs": map[string]interface{}{ - "average_rating": map[string]interface{}{ - "avg": map[string]interface{}{ - "field": "reviews.rating", - }, - }, - "by_reviewer": map[string]interface{}{ - "terms": map[string]interface{}{ - "field": "reviews.reviewer.keyword", - }, - "aggs": map[string]interface{}{ - "max_reviewer_rating": map[string]interface{}{ - "max": map[string]interface{}{ - "field": "reviews.rating", - }, - }, - }, - }, - }, - }, - }, - }, - }, - } - return query -} - -func Benchmark_Aggs_Builder(b *testing.B) { - createAggsQuery() - b.ResetTimer() - for i := 0; i < b.N; i++ { - createAggsQuery() - } -} - -func Benchmark_Aggs_Vanilla(b *testing.B) { - createAggsQueryVanilla() - b.ResetTimer() - for i := 0; i < b.N; i++ { - createAggsQueryVanilla() - } -} - -func Test_Aggs_Queries_are_equal(t *testing.T) { - builder := marshal.String(t, createAggsQuery()) - vanilla := marshal.String(t, createAggsQueryVanilla()) - assert.Equal(t, vanilla, builder) -} diff --git a/benchmarks/tests/complex_benchmark_test.go b/benchmarks/tests/complex_benchmark_test.go deleted file mode 100644 index cccd943..0000000 --- a/benchmarks/tests/complex_benchmark_test.go +++ /dev/null @@ -1,166 +0,0 @@ -package tests_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/benchmarks/tests/marshal" - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/es/enums/sort/order" - "github.com/Trendyol/es-query-builder/test/assert" -) - -func createComplexQuery(id int) map[string]any { - query := es.NewQuery( - es.Bool(). - Must( - es.Range("partition"). - GreaterThan(25). - LesserThanOrEqual(30), - es.Bool(). - Should( - es.Term("doc.id", id), - es.Term("file.fileId", id), - es.Term("page.number", id), - ), - ). - Filter( - es.Term("type", "File"), - es.Terms("sector", 1, 2, 3), - ). - MustNot( - es.Exists("blocks.reason.id"), - ). - MinimumShouldMatch(1). - Boost(3.14)). - Size(100). - From(5000). - Sort( - es.Sort("modifiedDate").Order(order.Desc), - es.Sort("name").Order(order.Asc), - es.Sort("indexedAt").Order(order.Asc), - ). - SourceIncludes("id", "type", "indexedAt", "chapters"). - SourceExcludes("private.key", "cipher") - - return query -} - -func createComplexQueryVanilla(id int) map[string]any { - query := map[string]interface{}{ - "_source": map[string]interface{}{ - "includes": []interface{}{"id", "type", "indexedAt", "chapters"}, - "excludes": []interface{}{"private.key", "cipher"}, - }, - "size": 100, - "from": 5000, - "sort": []map[string]interface{}{ - { - "modifiedDate": map[string]interface{}{ - "order": "desc", - }, - }, - { - "name": map[string]interface{}{ - "order": "asc", - }, - }, - { - "indexedAt": map[string]interface{}{ - "order": "asc", - }, - }, - }, - "query": map[string]interface{}{ - "bool": map[string]interface{}{ - "minimum_should_match": 1, - "boost": 3.14, - "must": []map[string]interface{}{ - { - "range": map[string]interface{}{ - "partition": map[string]interface{}{ - "gt": 25, - "lte": 30, - }, - }, - }, - { - "bool": map[string]interface{}{ - "should": []map[string]interface{}{ - { - "term": map[string]interface{}{ - "doc.id": map[string]interface{}{ - "value": id, - }, - }, - }, - { - "term": map[string]interface{}{ - "file.fileId": map[string]interface{}{ - "value": id, - }, - }, - }, - { - "term": map[string]interface{}{ - "page.number": map[string]interface{}{ - "value": id, - }, - }, - }, - }, - }, - }, - }, - "filter": []map[string]interface{}{ - { - "term": map[string]interface{}{ - "type": map[string]interface{}{ - "value": "File", - }, - }, - }, - { - "terms": map[string]interface{}{ - "sector": []interface{}{ - 1, 2, 3, - }, - }, - }, - }, - "must_not": []map[string]interface{}{ - { - "exists": map[string]interface{}{ - "field": "blocks.reason.id", - }, - }, - }, - }, - }, - } - return query -} - -func Benchmark_Complex_Builder(b *testing.B) { - id := 76 - createComplexQuery(id) - b.ResetTimer() - for i := 0; i < b.N; i++ { - createComplexQuery(id) - } -} - -func Benchmark_Complex_Vanilla(b *testing.B) { - id := 76 - createComplexQueryVanilla(id) - b.ResetTimer() - for i := 0; i < b.N; i++ { - createComplexQueryVanilla(id) - } -} - -func Test_Complex_Queries_are_equal(t *testing.T) { - id := 76 - build := marshal.String(t, createComplexQuery(id)) - vanilla := marshal.String(t, createComplexQueryVanilla(id)) - assert.Equal(t, vanilla, build) -} diff --git a/benchmarks/tests/conditional_benchmark_test.go b/benchmarks/tests/conditional_benchmark_test.go deleted file mode 100644 index 064cddb..0000000 --- a/benchmarks/tests/conditional_benchmark_test.go +++ /dev/null @@ -1,135 +0,0 @@ -package tests_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/benchmarks/tests/marshal" - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/es/enums/sort/order" - "github.com/Trendyol/es-query-builder/test/assert" -) - -func createConditionalQuery(items []int) map[string]any { - query := es.NewQuery( - es.Bool(). - Filter( - es.Range("indexedAt"). - GreaterThan("2021-01-01"). - LesserThanOrEqual("now"), - es.Term("type", "File"), - es.Terms("sector", 1, 2, 3), - es.TermsFunc("id", items, func(key string, values []int) bool { - for _, value := range values { - if value == 21 { - return false - } - } - return true - }), - ). - MustNot( - es.Exists("blocks.reason.id"), - )). - Size(100). - Sort( - es.Sort("modifiedDate").Order(order.Desc), - ). - SourceIncludes("id", "type", "indexedAt", "chapters"). - SourceExcludes("private.key") - - return query -} - -func createConditionalQueryVanilla(items []int) map[string]any { - var flag bool - for _, item := range items { - if item == 21 { - flag = false - break - } - flag = true - } - - filter := []map[string]interface{}{ - { - "range": map[string]interface{}{ - "indexedAt": map[string]interface{}{ - "gt": "2021-01-01", - "lte": "now", - }, - }, - }, - { - "term": map[string]interface{}{ - "type": map[string]interface{}{ - "value": "File", - }, - }, - }, - { - "terms": map[string]interface{}{ - "sector": []interface{}{1, 2, 3}, - }, - }, - } - if flag { - filter = append(filter, map[string]interface{}{ - "terms": map[string]interface{}{ - "id": items, - }, - }) - } - - query := map[string]interface{}{ - "_source": map[string]interface{}{ - "includes": []interface{}{"id", "type", "indexedAt", "chapters"}, - "excludes": []interface{}{"private.key"}, - }, - "size": 100, - "sort": []map[string]interface{}{ - { - "modifiedDate": map[string]interface{}{ - "order": "desc", - }, - }, - }, - "query": map[string]interface{}{ - "bool": map[string]interface{}{ - "filter": filter, - "must_not": []map[string]interface{}{ - { - "exists": map[string]interface{}{ - "field": "blocks.reason.id", - }, - }, - }, - }, - }, - } - return query -} - -func Benchmark_Conditional_Builder(b *testing.B) { - items := []int{1, 1, 2, 3, 5, 8, 13, 21, 34, 55} - createConditionalQuery(items) - b.ResetTimer() - for i := 0; i < b.N; i++ { - createConditionalQuery(items) - } -} - -func Benchmark_Conditional_Vanilla(b *testing.B) { - items := []int{1, 1, 2, 3, 5, 8, 13, 21, 34, 55} - createConditionalQueryVanilla(items) - b.ResetTimer() - for i := 0; i < b.N; i++ { - createConditionalQueryVanilla(items) - } -} - -func Test_Conditional_Queries_are_equal(t *testing.T) { - items := []int{1, 1, 2, 3, 5, 8, 13, 21, 34, 55} - build := marshal.String(t, createConditionalQuery(items)) - vanilla := marshal.String(t, createConditionalQueryVanilla(items)) - assert.Equal(t, vanilla, build) -} diff --git a/benchmarks/tests/intermediate_benchmark_test.go b/benchmarks/tests/intermediate_benchmark_test.go deleted file mode 100644 index c9e7b59..0000000 --- a/benchmarks/tests/intermediate_benchmark_test.go +++ /dev/null @@ -1,107 +0,0 @@ -package tests_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/benchmarks/tests/marshal" - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/es/enums/sort/order" - "github.com/Trendyol/es-query-builder/test/assert" -) - -func createIntermediateQuery(id int) map[string]any { - query := es.NewQuery( - es.Bool(). - Must( - es.Bool(). - Should( - es.Term("doc.id", id), - es.Term("file.fileId", id), - ), - ). - Filter( - es.Terms("type", "DOC", "FILE"), - )). - Size(45). - Sort(es.Sort("name").Order(order.Asc)). - SourceIncludes("id", "type", "indexedAt", "chapters") - - return query -} - -func createIntermediateQueryVanilla(id int) map[string]any { - query := map[string]interface{}{ - "_source": map[string]interface{}{ - "includes": []interface{}{"id", "type", "indexedAt", "chapters"}, - }, - "size": 45, - "sort": []map[string]interface{}{ - { - "name": map[string]interface{}{ - "order": "asc", - }, - }, - }, - "query": map[string]interface{}{ - "bool": map[string]interface{}{ - "must": []interface{}{ - map[string]interface{}{ - "bool": map[string]interface{}{ - "should": []interface{}{ - map[string]interface{}{ - "term": map[string]interface{}{ - "doc.id": map[string]interface{}{ - "value": id, - }, - }, - }, - map[string]interface{}{ - "term": map[string]interface{}{ - "file.fileId": map[string]interface{}{ - "value": id, - }, - }, - }, - }, - }, - }, - }, - "filter": []interface{}{ - map[string]interface{}{ - "terms": map[string]interface{}{ - "type": []string{ - "DOC", "FILE", - }, - }, - }, - }, - }, - }, - } - return query -} - -func Benchmark_Intermediate_Builder(b *testing.B) { - id := 42 - createIntermediateQuery(id) - b.ResetTimer() - for i := 0; i < b.N; i++ { - createIntermediateQuery(id) - } -} - -func Benchmark_Intermediate_Vanilla(b *testing.B) { - id := 42 - createIntermediateQueryVanilla(id) - b.ResetTimer() - for i := 0; i < b.N; i++ { - createIntermediateQueryVanilla(id) - } -} - -func Test_Intermediate_Queries_are_equal(t *testing.T) { - id := 42 - build := marshal.String(t, createIntermediateQuery(id)) - vanilla := marshal.String(t, createIntermediateQueryVanilla(id)) - assert.Equal(t, vanilla, build) -} diff --git a/benchmarks/tests/marshal/marshal_string.go b/benchmarks/tests/marshal/marshal_string.go deleted file mode 100644 index 76abe67..0000000 --- a/benchmarks/tests/marshal/marshal_string.go +++ /dev/null @@ -1,14 +0,0 @@ -package marshal - -import ( - "encoding/json" - "testing" - - "github.com/Trendyol/es-query-builder/test/assert" -) - -func String(t *testing.T, query map[string]any) string { - marshal, err := json.Marshal(query) - assert.Nil(t, err) - return string(marshal) -} diff --git a/benchmarks/tests/mixed_benchmark_test.go b/benchmarks/tests/mixed_benchmark_test.go deleted file mode 100644 index b863c74..0000000 --- a/benchmarks/tests/mixed_benchmark_test.go +++ /dev/null @@ -1,122 +0,0 @@ -package tests_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/benchmarks/tests/marshal" - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/test/assert" -) - -func createMixedQuery() map[string]any { - query := es.NewQuery( - es.Bool(). - Must( - es.Term("author", "George Orwell"), - ). - MustNot( - es.Terms("genre", "Fantasy", "Science Fiction"), - es.Exists("out_of_print"), - ). - Should( - es.Terms("title", "1984", "Animal Farm"), - ), - ).Aggs("genres_count", - es.AggTerms(). - Field("genre"), - ).Aggs("authors_and_genres", - es.AggTerms(). - Field("author"). - Aggs("genres", - es.AggTerms(). - Field("genre"), - ), - ) - - return query -} - -func createMixedQueryVanilla() map[string]any { - query := map[string]interface{}{ - "query": map[string]interface{}{ - "bool": map[string]interface{}{ - "must": []map[string]interface{}{ - { - "term": map[string]interface{}{ - "author": map[string]interface{}{ - "value": "George Orwell", - }, - }, - }, - }, - "must_not": []map[string]interface{}{ - { - "terms": map[string]interface{}{ - "genre": []string{ - "Fantasy", - "Science Fiction", - }, - }, - }, - { - "exists": map[string]interface{}{ - "field": "out_of_print", - }, - }, - }, - "should": []map[string]interface{}{ - { - "terms": map[string]interface{}{ - "title": []string{ - "1984", - "Animal Farm", - }, - }, - }, - }, - }, - }, - "aggs": map[string]interface{}{ - "genres_count": map[string]interface{}{ - "terms": map[string]interface{}{ - "field": "genre", - }, - }, - "authors_and_genres": map[string]interface{}{ - "terms": map[string]interface{}{ - "field": "author", - }, - "aggs": map[string]interface{}{ - "genres": map[string]interface{}{ - "terms": map[string]interface{}{ - "field": "genre", - }, - }, - }, - }, - }, - } - return query -} - -func Benchmark_Mixed_Builder(b *testing.B) { - createMixedQuery() - b.ResetTimer() - for i := 0; i < b.N; i++ { - createMixedQuery() - } -} - -func Benchmark_Mixed_Vanilla(b *testing.B) { - createMixedQueryVanilla() - b.ResetTimer() - for i := 0; i < b.N; i++ { - createMixedQueryVanilla() - } -} - -func Test_Mixed_Queries_are_equal(t *testing.T) { - build := marshal.String(t, createMixedQuery()) - vanilla := marshal.String(t, createMixedQueryVanilla()) - assert.Equal(t, vanilla, build) -} diff --git a/benchmarks/tests/nested_benchmark_test.go b/benchmarks/tests/nested_benchmark_test.go deleted file mode 100644 index a184b21..0000000 --- a/benchmarks/tests/nested_benchmark_test.go +++ /dev/null @@ -1,83 +0,0 @@ -package tests_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/benchmarks/tests/marshal" - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/test/assert" -) - -func createNestedQuery() map[string]any { - query := es.NewQuery( - es.Nested("driver", - es.Nested("driver.vehicle", - es.Bool(). - Must( - es.Term("driver.vehicle.make", "Powell Motors"), - es.Term("driver.vehicle.model", "Canyonero"), - ), - ), - ), - ) - - return query -} - -func createNestedQueryVanilla() map[string]any { - query := map[string]interface{}{ - "query": map[string]interface{}{ - "nested": map[string]interface{}{ - "path": "driver", - "query": map[string]interface{}{ - "nested": map[string]interface{}{ - "path": "driver.vehicle", - "query": map[string]interface{}{ - "bool": map[string]interface{}{ - "must": []map[string]interface{}{ - { - "term": map[string]interface{}{ - "driver.vehicle.make": map[string]interface{}{ - "value": "Powell Motors", - }, - }, - }, - { - "term": map[string]interface{}{ - "driver.vehicle.model": map[string]interface{}{ - "value": "Canyonero", - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - } - return query -} - -func Benchmark_Nested_Builder(b *testing.B) { - createNestedQuery() - b.ResetTimer() - for i := 0; i < b.N; i++ { - createNestedQuery() - } -} - -func Benchmark_Nested_Vanilla(b *testing.B) { - createNestedQueryVanilla() - b.ResetTimer() - for i := 0; i < b.N; i++ { - createNestedQueryVanilla() - } -} - -func Test_Nested_Queries_are_equal(t *testing.T) { - build := marshal.String(t, createNestedQuery()) - vanilla := marshal.String(t, createNestedQueryVanilla()) - assert.Equal(t, vanilla, build) -} diff --git a/benchmarks/tests/simple_benchmark_test.go b/benchmarks/tests/simple_benchmark_test.go deleted file mode 100644 index 9f010b9..0000000 --- a/benchmarks/tests/simple_benchmark_test.go +++ /dev/null @@ -1,60 +0,0 @@ -package tests_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/benchmarks/tests/marshal" - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/test/assert" -) - -func createSimpleQuery() map[string]any { - query := es.NewQuery( - es.Bool(). - Filter( - es.Term("id", 123456), - ), - ) - return query -} - -func createSimpleQueryVanilla() map[string]any { - query := map[string]interface{}{ - "query": map[string]interface{}{ - "bool": map[string]interface{}{ - "filter": []map[string]interface{}{ - { - "term": map[string]interface{}{ - "id": map[string]interface{}{ - "value": 123456, - }, - }, - }, - }, - }, - }, - } - return query -} - -func Benchmark_Simple_Builder(b *testing.B) { - createSimpleQuery() - b.ResetTimer() - for i := 0; i < b.N; i++ { - createSimpleQuery() - } -} - -func Benchmark_Simple_Vanilla(b *testing.B) { - createSimpleQueryVanilla() - b.ResetTimer() - for i := 0; i < b.N; i++ { - createSimpleQueryVanilla() - } -} - -func Test_Simple_Queries_are_equal(t *testing.T) { - build := marshal.String(t, createSimpleQuery()) - vanilla := marshal.String(t, createSimpleQueryVanilla()) - assert.Equal(t, vanilla, build) -} diff --git a/benchmarks/tests/ty_example_benchmark_test.go b/benchmarks/tests/ty_example_benchmark_test.go deleted file mode 100644 index bcdb2fa..0000000 --- a/benchmarks/tests/ty_example_benchmark_test.go +++ /dev/null @@ -1,83 +0,0 @@ -package tests_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/benchmarks/tests/marshal" - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/test/assert" -) - -func createTyExampleQuery(brandIds []int64, storefrontIds []string) map[string]any { - query := es.NewQuery( - es.Bool(). - Filter( - es.Term("type", "LegalRule"), - es.TermsArray("brandId", brandIds), - es.TermsArray("allowedStorefronts.storefrontId", storefrontIds), - ), - ) - query.Size(1) - query.SourceFalse() - - return query -} - -func createTyExampleQueryVanilla(brandIds []int64, storefrontIds []string) map[string]any { - query := map[string]interface{}{ - "size": 1, - "query": map[string]interface{}{ - "bool": map[string]interface{}{ - "filter": []interface{}{ - map[string]interface{}{ - "term": map[string]interface{}{ - "type": map[string]interface{}{ - "value": "LegalRule", - }, - }, - }, - map[string]interface{}{ - "terms": map[string]interface{}{ - "brandId": brandIds, - }, - }, - map[string]interface{}{ - "terms": map[string]interface{}{ - "allowedStorefronts.storefrontId": storefrontIds, - }, - }, - }, - }, - }, - "_source": false, - } - return query -} - -func Benchmark_Ty_Example_Builder(b *testing.B) { - brandIds := []int64{11, 22, 33, 44} - storefrontIds := []string{"35", "36", "43", "48", "49", "50"} - createTyExampleQuery(brandIds, storefrontIds) - b.ResetTimer() - for i := 0; i < b.N; i++ { - createTyExampleQuery(brandIds, storefrontIds) - } -} - -func Benchmark_Ty_Example_Vanilla(b *testing.B) { - brandIds := []int64{11, 22, 33, 44} - storefrontIds := []string{"35", "36", "43", "48", "49", "50"} - createTyExampleQueryVanilla(brandIds, storefrontIds) - b.ResetTimer() - for i := 0; i < b.N; i++ { - createTyExampleQueryVanilla(brandIds, storefrontIds) - } -} - -func Test_Ty_Example_Queries_are_equal(t *testing.T) { - brandIds := []int64{11, 22, 33, 44} - storefrontIds := []string{"35", "36", "43", "48", "49", "50"} - build := marshal.String(t, createTyExampleQuery(brandIds, storefrontIds)) - vanilla := marshal.String(t, createTyExampleQueryVanilla(brandIds, storefrontIds)) - assert.Equal(t, vanilla, build) -} diff --git a/es/aggregations.go b/es/aggregations.go deleted file mode 100644 index e293c35..0000000 --- a/es/aggregations.go +++ /dev/null @@ -1,388 +0,0 @@ -package es - -import Order "github.com/Trendyol/es-query-builder/es/enums/sort/order" - -type aggsType Object - -type aggTermType Object - -// AggTerm creates a new aggregation term with the specified field. -// -// This function initializes an aggregation term with the given field name. -// It can be used to specify a field for aggregation operations in queries. -// -// Example usage: -// -// termAgg := AggTerm("fieldName") -// // termAgg now has the "field" set to "fieldName". -// -// Parameters: -// - field: The name of the field to aggregate on. -// -// Returns: -// -// An aggTermType object with the "field" set to the provided value. -func AggTerm(field string) aggTermType { - return aggTermType{ - "field": field, - } -} - -// Missing sets the "missing" value for an aggregation term. -// -// This method specifies a value to be used when the field is missing in documents. -// It updates the aggTermType object to handle missing values in the aggregation. -// -// Example usage: -// -// termAgg := AggTerm("fieldName").Missing("N/A") -// // termAgg now has the "missing" field set to "N/A". -// -// Parameters: -// - missing: The value to use when the field is missing. -// -// Returns: -// -// The updated aggTermType object with the "missing" field set to the specified value. -func (aggTerm aggTermType) Missing(missing string) aggTermType { - aggTerm["missing"] = missing - return aggTerm -} - -// AggTerms creates a new "terms" aggregation. -// -// This function initializes an aggregation for terms. It can be used to perform -// aggregation based on the unique terms of a field. -// -// Example usage: -// -// termsAgg := AggTerms() -// // termsAgg now has the "terms" field initialized. -// -// Returns: -// -// An aggsType object with the "terms" field initialized. -func AggTerms() aggsType { - return aggsType{ - "terms": Object{}, - } -} - -// AggMultiTerms creates a new "multi_terms" aggregation. -// -// This function initializes an aggregation for multiple terms. It can be used -// to perform aggregation based on multiple fields or term combinations. -// -// Example usage: -// -// multiTermsAgg := AggMultiTerms() -// // multiTermsAgg now has the "multi_terms" field initialized. -// -// Returns: -// -// An aggsType object with the "multi_terms" field initialized. -func AggMultiTerms() aggsType { - return aggsType{ - "multi_terms": Object{}, - } -} - -// AggNested creates a new "nested" aggregation. -// -// This function initializes an aggregation for nested fields. It can be used to -// perform aggregations on fields that are within a nested object. -// -// Example usage: -// -// nestedAgg := AggNested() -// // nestedAgg now has the "nested" field initialized. -// -// Returns: -// -// An aggsType object with the "nested" field initialized. -func AggNested() aggsType { - return aggsType{ - "nested": Object{}, - } -} - -// AggMax creates a new "max" aggregation. -// -// This function initializes an aggregation to calculate the maximum value of a field. -// -// Example usage: -// -// maxAgg := AggMax() -// // maxAgg now has the "max" field initialized. -// -// Returns: -// -// An aggsType object with the "max" field initialized. -func AggMax() aggsType { - return aggsType{ - "max": Object{}, - } -} - -// AggMin creates a new "min" aggregation. -// -// This function initializes an aggregation to calculate the minimum value of a field. -// -// Example usage: -// -// minAgg := AggMin() -// // minAgg now has the "min" field initialized. -// -// Returns: -// -// An aggsType object with the "min" field initialized. -func AggMin() aggsType { - return aggsType{ - "min": Object{}, - } -} - -// AggAvg creates a new "avg" aggregation. -// -// This function initializes an aggregation to calculate the average value of a field. -// -// Example usage: -// -// avgAgg := AggAvg() -// // avgAgg now has the "avg" field initialized. -// -// Returns: -// -// An aggsType object with the "avg" field initialized. -func AggAvg() aggsType { - return aggsType{ - "avg": Object{}, - } -} - -// AggCustom creates a custom aggregation with the provided aggregation object. -// -// This function initializes an aggregation based on the given custom aggregation definition. -// -// Example usage: -// -// customAgg := AggCustom(Object{"custom": "value"}) -// // customAgg now has the custom aggregation specified. -// -// Parameters: -// - agg: An es.Object representing a custom aggregation definition. -// -// Returns: -// -// An aggsType object initialized with the provided custom aggregation. -func AggCustom(agg Object) aggsType { - return aggsType(agg) -} - -func (agg aggsType) putInTheField(key string, value any) aggsType { - for _, fieldObj := range agg { - if fieldObject, ok := fieldObj.(Object); ok { - fieldObject[key] = value - break - } - } - return agg -} - -// Aggs adds a nested aggregation to the aggsType object. -// -// This method adds a nested aggregation under the "aggs" field with the given name. -// -// Example usage: -// -// nestedAgg := AggTerms().Size(5) -// agg := AggTerms().Aggs("nested", nestedAgg) -// // agg now has a nested aggregation named "nested" with the specified aggregation. -// -// Parameters: -// - name: The name of the nested aggregation. -// - nestedAgg: The nested aggregation to add. -// -// Returns: -// -// The updated aggsType object with the nested aggregation added. -func (agg aggsType) Aggs(name string, nestedAgg aggsType) aggsType { - aggs, ok := agg["aggs"].(Object) - if !ok { - aggs = Object{} - } - aggs[name] = nestedAgg - agg["aggs"] = aggs - return agg -} - -// Field sets the "field" value in the aggsType object. -// -// This method specifies the field to aggregate on in the aggsType object. -// -// Example usage: -// -// agg := AggTerms().Field("fieldName") -// // agg now has the "field" set to "fieldName". -// -// Parameters: -// - field: The name of the field to aggregate on. -// -// Returns: -// -// The updated aggsType object with the "field" set to the specified value. -func (agg aggsType) Field(field string) aggsType { - return agg.putInTheField("field", field) -} - -// Path sets the "path" value in the aggsType object. -// -// This method specifies the nested path for the aggregation in the aggsType object. -// -// Example usage: -// -// agg := AggNested().Path("nestedField.path") -// // agg now has the "path" set to "nestedField.path". -// -// Parameters: -// - path: The nested path to use for the aggregation. -// -// Returns: -// -// The updated aggsType object with the "path" set to the specified value. -func (agg aggsType) Path(path string) aggsType { - return agg.putInTheField("path", path) -} - -// Size sets the "size" value in the aggsType object. -// -// This method specifies the number of terms to return in the aggregation result. -// -// Example usage: -// -// agg := AggTerms().Size(10) -// // agg now has the "size" field set to 10. -// -// Parameters: -// - size: The number of terms to return. -// -// Returns: -// -// The updated aggsType object with the "size" field set to the specified value. -func (agg aggsType) Size(size int) aggsType { - return agg.putInTheField("size", size) -} - -// Order sets the "order" field in the aggsType object. -// -// This method specifies the sorting order for the aggregation results. -// -// Example usage: -// -// agg := AggTerms().Order("fieldName", Order.Desc) -// // agg now has the "order" field set to "desc" for "fieldName". -// -// Parameters: -// - field: The name of the field to sort by. -// - order: The Order value specifying the sorting direction (e.g., Asc or Desc). -// -// Returns: -// -// The updated aggsType object with the "order" field set to the specified value. -func (agg aggsType) Order(field string, order Order.Order) aggsType { - return agg.putInTheField("order", - Object{ - field: order, - }, - ) -} - -// Include sets the "include" field in the aggsType object. -// -// This method specifies a pattern to include in the aggregation results. -// -// Example usage: -// -// agg := AggTerms().Include("pattern*") -// // agg now has the "include" field set to "pattern*". -// -// Parameters: -// - include: The pattern to include in the aggregation results. -// -// Returns: -// -// The updated aggsType object with the "include" field set to the specified value. -func (agg aggsType) Include(include string) aggsType { - return agg.putInTheField("include", include) -} - -// Exclude sets the "exclude" field in the aggsType object. -// -// This method specifies a pattern to exclude from the aggregation results. -// -// Example usage: -// -// agg := AggTerms().Exclude("pattern*") -// // agg now has the "exclude" field set to "pattern*". -// -// Parameters: -// - exclude: The pattern to exclude from the aggregation results. -// -// Returns: -// -// The updated aggsType object with the "exclude" field set to the specified value. -func (agg aggsType) Exclude(exclude string) aggsType { - return agg.putInTheField("exclude", exclude) -} - -// Terms sets the "terms" field in the aggsType object. -// -// This method adds a list of aggregation terms to the "terms" field of the aggsType object. -// It allows specifying multiple term aggregations for the aggregation query. -// -// Example usage: -// -// agg := AggTerms(). -// Terms( -// AggTerm("field1"), -// AggTerm("field2"), -// ) -// // agg now has the "terms" field containing the provided term aggregations. -// -// Parameters: -// - terms: A variadic list of aggTermType objects representing the term aggregations. -// -// Returns: -// -// The updated aggsType object with the "terms" field set to the provided term aggregations. -func (agg aggsType) Terms(terms ...aggTermType) aggsType { - return agg.putInTheField("terms", terms) -} - -// Aggs adds a named aggregation to the "aggs" field of the es.Object. -// -// This method allows adding a nested aggregation under the "aggs" field in the es.Object. -// It associates the given name with the specified aggregation, enabling complex aggregation queries. -// -// Example usage: -// -// termAgg := AggTerms().Field("fieldName") -// query := es.NewQuery().Aggs("myAgg", termAgg) -// // query now has an "aggs" field with a nested aggregation named "myAgg". -// -// Parameters: -// - name: The name to associate with the nested aggregation. -// - agg: The aggsType object representing the nested aggregation. -// -// Returns: -// -// The updated Object with the "aggs" field containing the new named aggregation. -func (o Object) Aggs(name string, agg aggsType) Object { - aggs, ok := o["aggs"].(Object) - if !ok { - aggs = Object{} - } - aggs[name] = agg - o["aggs"] = aggs - return o -} diff --git a/es/aggregations_test.go b/es/aggregations_test.go deleted file mode 100644 index 48f7e1e..0000000 --- a/es/aggregations_test.go +++ /dev/null @@ -1,432 +0,0 @@ -package es_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/test/assert" - - Order "github.com/Trendyol/es-query-builder/es/enums/sort/order" -) - -//// AGGS //// - -func Test_AggTerm_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.AggTerm) -} - -func Test_AggTerm_method_should_create_aggTermType(t *testing.T) { - // Given - a := es.AggTerm("path") - - // Then - assert.NotNil(t, a) - assert.IsTypeString(t, "es.aggTermType", a) -} - -func Test_AggTerm_should_create_json_with_field_field_inside(t *testing.T) { - // Given - a := es.AggTerm("path") - - // When Then - assert.NotNil(t, a) - bodyJSON := assert.MarshalWithoutError(t, a) - assert.Equal(t, "{\"field\":\"path\"}", bodyJSON) -} - -func Test_AggTerm_should_have_Missing_method(t *testing.T) { - // Given - a := es.AggTerm("path") - - // When Then - assert.NotNil(t, a.Missing) -} - -func Test_Missing_should_add_missing_field_into_AggTerm(t *testing.T) { - // Given - a := es.AggTerm("path").Missing("missing_name") - - // When Then - assert.NotNil(t, a) - bodyJSON := assert.MarshalWithoutError(t, a) - assert.Equal(t, "{\"field\":\"path\",\"missing\":\"missing_name\"}", bodyJSON) -} - -func Test_AggTerms_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.AggTerms) -} - -func Test_AggTerms_method_should_create_aggType(t *testing.T) { - // Given - a := es.AggTerms() - - // Then - assert.NotNil(t, a) - assert.IsTypeString(t, "es.aggsType", a) -} - -func Test_AggTerms_should_create_json_with_terms_field_inside(t *testing.T) { - // Given - a := es.AggTerms() - - // When Then - assert.NotNil(t, a) - bodyJSON := assert.MarshalWithoutError(t, a) - assert.Equal(t, "{\"terms\":{}}", bodyJSON) -} - -func Test_AggMultiTerms_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.AggMultiTerms) -} - -func Test_AggMultiTerms_method_should_create_aggType(t *testing.T) { - // Given - a := es.AggMultiTerms() - - // Then - assert.NotNil(t, a) - assert.IsTypeString(t, "es.aggsType", a) -} - -func Test_AggMultiTerms_should_create_json_with_multi_terms_field_inside(t *testing.T) { - // Given - a := es.AggMultiTerms() - - // When Then - assert.NotNil(t, a) - bodyJSON := assert.MarshalWithoutError(t, a) - assert.Equal(t, "{\"multi_terms\":{}}", bodyJSON) -} - -func Test_AggNested_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.AggNested) -} - -func Test_AggNested_method_should_create_aggType(t *testing.T) { - // Given - a := es.AggNested() - - // Then - assert.NotNil(t, a) - assert.IsTypeString(t, "es.aggsType", a) -} - -func Test_AggNested_should_create_json_with_nested_field_inside(t *testing.T) { - // Given - a := es.AggNested() - - // When Then - assert.NotNil(t, a) - bodyJSON := assert.MarshalWithoutError(t, a) - assert.Equal(t, "{\"nested\":{}}", bodyJSON) -} - -func Test_AggCustom_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.AggCustom) -} - -func Test_AggCustom_method_should_create_aggType(t *testing.T) { - // Given - a := es.AggCustom(nil) - - // Then - assert.NotNil(t, a) - assert.IsTypeString(t, "es.aggsType", a) -} - -func Test_AggCustom_should_create_json(t *testing.T) { - // Given - a := es.AggCustom(es.Object{ - "custom": es.Object{ - "my_field": es.Array{1, 2, 3}, - }, - }) - - // When Then - assert.NotNil(t, a) - bodyJSON := assert.MarshalWithoutError(t, a) - assert.Equal(t, "{\"custom\":{\"my_field\":[1,2,3]}}", bodyJSON) -} - -func Test_AggType_should_have_Field_method(t *testing.T) { - // Given - a := es.AggTerms() - - // When Then - assert.NotNil(t, a.Field) -} - -func Test_Field_should_add_field_field_into_AggTerm(t *testing.T) { - // Given - a := es.AggTerms().Field("path") - - // When Then - assert.NotNil(t, a) - bodyJSON := assert.MarshalWithoutError(t, a) - assert.Equal(t, "{\"terms\":{\"field\":\"path\"}}", bodyJSON) -} - -func Test_AggType_should_have_Path_method(t *testing.T) { - // Given - a := es.AggTerms() - - // When Then - assert.NotNil(t, a.Path) -} - -func Test_Path_should_add_path_field_into_AggNested(t *testing.T) { - // Given - a := es.AggNested().Path("review") - - // When Then - assert.NotNil(t, a) - bodyJSON := assert.MarshalWithoutError(t, a) - assert.Equal(t, "{\"nested\":{\"path\":\"review\"}}", bodyJSON) -} - -func Test_AggType_should_have_Size_method(t *testing.T) { - // Given - a := es.AggTerms() - - // When Then - assert.NotNil(t, a.Size) -} - -func Test_Size_should_add_size_field_into_AggType(t *testing.T) { - // Given - a := es.AggTerms().Size(333) - - // When Then - assert.NotNil(t, a) - bodyJSON := assert.MarshalWithoutError(t, a) - assert.Equal(t, "{\"terms\":{\"size\":333}}", bodyJSON) -} - -func Test_AggType_should_have_Order_method(t *testing.T) { - // Given - a := es.AggTerms() - - // When Then - assert.NotNil(t, a.Field) -} - -func Test_Order_should_add_order_field_into_AggType(t *testing.T) { - // Given - a := es.AggTerms().Order("path", Order.Desc) - - // When Then - assert.NotNil(t, a) - bodyJSON := assert.MarshalWithoutError(t, a) - assert.Equal(t, "{\"terms\":{\"order\":{\"path\":\"desc\"}}}", bodyJSON) -} - -func Test_AggType_should_have_Include_method(t *testing.T) { - // Given - a := es.AggTerms() - - // When Then - assert.NotNil(t, a.Include) -} - -func Test_Include_should_add_include_field_into_AggType(t *testing.T) { - // Given - a := es.AggTerms().Include("*.2024") - - // When Then - assert.NotNil(t, a) - bodyJSON := assert.MarshalWithoutError(t, a) - assert.Equal(t, "{\"terms\":{\"include\":\"*.2024\"}}", bodyJSON) -} - -func Test_AggType_should_have_Exclude_method(t *testing.T) { - // Given - a := es.AggTerms() - - // When Then - assert.NotNil(t, a.Exclude) -} - -func Test_Exclude_should_add_exclude_field_into_AggType(t *testing.T) { - // Given - a := es.AggTerms().Exclude("*.2021") - - // When Then - assert.NotNil(t, a) - bodyJSON := assert.MarshalWithoutError(t, a) - assert.Equal(t, "{\"terms\":{\"exclude\":\"*.2021\"}}", bodyJSON) -} - -func Test_AggType_should_have_Terms_method(t *testing.T) { - // Given - a := es.AggTerms() - - // When Then - assert.NotNil(t, a.Terms) -} - -func Test_AggMax_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.AggMax) -} - -func Test_AggMax_method_should_create_aggType(t *testing.T) { - // Given - a := es.AggMax() - - // Then - assert.NotNil(t, a) - assert.IsTypeString(t, "es.aggsType", a) -} - -func Test_AggMax_should_create_json_with_terms_field_inside(t *testing.T) { - // Given - a := es.AggMax() - - // When Then - assert.NotNil(t, a) - bodyJSON := assert.MarshalWithoutError(t, a) - assert.Equal(t, "{\"max\":{}}", bodyJSON) -} - -//// Agg.Min //// - -func Test_AggMin_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.AggMin) -} - -func Test_AggMin_method_should_create_aggType(t *testing.T) { - // Given - a := es.AggMin() - - // Then - assert.NotNil(t, a) - assert.IsTypeString(t, "es.aggsType", a) -} - -func Test_AggMin_should_create_json_with_terms_field_inside(t *testing.T) { - // Given - a := es.AggMin() - - // When Then - assert.NotNil(t, a) - bodyJSON := assert.MarshalWithoutError(t, a) - assert.Equal(t, "{\"min\":{}}", bodyJSON) -} - -//// Agg.Avg //// - -func Test_AggAvg_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.AggAvg) -} - -func Test_AggAvg_method_should_create_aggType(t *testing.T) { - // Given - a := es.AggAvg() - - // Then - assert.NotNil(t, a) - assert.IsTypeString(t, "es.aggsType", a) -} - -func Test_AggAvg_should_create_json_with_terms_field_inside(t *testing.T) { - // Given - a := es.AggAvg() - - // When Then - assert.NotNil(t, a) - bodyJSON := assert.MarshalWithoutError(t, a) - assert.Equal(t, "{\"avg\":{}}", bodyJSON) -} - -func Test_Terms_should_add_terms_field_into_AggType(t *testing.T) { - // Given - a := es.AggMultiTerms(). - Terms( - es.AggTerm("A1"), - es.AggTerm("B2"). - Missing("Hell Divers"), - es.AggTerm("C3"), - es.AggTerm("D4"), - ) - - // When Then - assert.NotNil(t, a) - bodyJSON := assert.MarshalWithoutError(t, a) - // nolint:golint,lll - assert.Equal(t, "{\"multi_terms\":{\"terms\":[{\"field\":\"A1\"},{\"field\":\"B2\",\"missing\":\"Hell Divers\"},{\"field\":\"C3\"},{\"field\":\"D4\"}]}}", bodyJSON) -} - -func Test_AggType_should_have_Aggs_method(t *testing.T) { - // Given - a := es.AggTerms() - - // When Then - assert.NotNil(t, a.Aggs) -} - -func Test_Aggs_should_add_aggs_field_into_AggType(t *testing.T) { - // Given - a := es.AggTerms(). - Field("path"). - Size(1_000). - Order("_key", Order.Asc). - Include("reduces"). - Aggs("test", - es.AggMultiTerms(). - Terms( - es.AggTerm("A1"). - Missing("a1"), - es.AggTerm("B2"), - ), - ) - - // When Then - assert.NotNil(t, a) - bodyJSON := assert.MarshalWithoutError(t, a) - // nolint:golint,lll - assert.Equal(t, "{\"aggs\":{\"test\":{\"multi_terms\":{\"terms\":[{\"field\":\"A1\",\"missing\":\"a1\"},{\"field\":\"B2\"}]}}},\"terms\":{\"field\":\"path\",\"include\":\"reduces\",\"order\":{\"_key\":\"asc\"},\"size\":1000}}", bodyJSON) -} - -func Test_Aggs_should_create_json_with_aggs_field_inside_query(t *testing.T) { - // Given - query := es.NewQuery(nil) - query.Aggs("types", - es.AggTerms(). - Field("type"). - Size(100), - ) - - // When Then - assert.NotNil(t, query) - assert.NotNil(t, query.Aggs) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"aggs\":{\"types\":{\"terms\":{\"field\":\"type\",\"size\":100}}},\"query\":{}}", bodyJSON) -} - -func Test_should_create_json_with_multiple_Aggs_inside_single_query(t *testing.T) { - // Given - query := es.NewQuery(nil). - Aggs("types", - es.AggTerms(). - Field("type"). - Size(100), - ). - Aggs("average_review_score", - es.AggAvg(). - Field("reviews.score"), - ) - - // When Then - assert.NotNil(t, query) - assert.NotNil(t, query.Aggs) - bodyJSON := assert.MarshalWithoutError(t, query) - // nolint:golint,lll - assert.Equal(t, "{\"aggs\":{\"average_review_score\":{\"avg\":{\"field\":\"reviews.score\"}},\"types\":{\"terms\":{\"field\":\"type\",\"size\":100}}},\"query\":{}}", bodyJSON) -} diff --git a/es/base_query.go b/es/base_query.go deleted file mode 100644 index 6fa4f30..0000000 --- a/es/base_query.go +++ /dev/null @@ -1,297 +0,0 @@ -package es - -import ( - Mode "github.com/Trendyol/es-query-builder/es/enums/sort/mode" - Order "github.com/Trendyol/es-query-builder/es/enums/sort/order" -) - -type sortType Object - -// NewQuery creates a new query es.Object with the provided query clause. -// -// This function takes any query clause as input and attempts to convert it into the correct internal type using the `correctType` function. -// If the conversion is successful, the resulting field is stored under the "query" key in the returned es.Object. -// If the conversion fails or the input is nil, an empty es.Object is returned under the "query" key. -// -// Example usage: -// -// termQuery := es.Term("fieldName", "value") -// query := es.NewQuery(termQuery) -// // query now contains a "query" field with the term query. -// -// Parameters: -// - queryClause: The query clause to be converted and added to the "query" field. It can be of any type. -// -// Returns: -// -// An Object containing the "query" field with the processed query clause. -func NewQuery(queryClause any) Object { - if field, ok := correctType(queryClause); ok { - return Object{ - "query": field, - } - } - return Object{ - "query": Object{}, - } -} - -// TrackTotalHits sets the "track_total_hits" parameter in an es.Object. -// -// This method allows you to specify whether the total number of hits should -// be tracked in the search results. When set to true, the total number of -// matching documents is included in the response. This is useful for -// pagination and to understand the overall size of the result set. -// -// Example usage: -// -// query := es.NewQuery(...).TrackTotalHits(true) -// // query now includes a "track_total_hits" parameter with a value of true. -// -// Parameters: -// - value: A boolean indicating whether to track the total number of hits. -// Set to true to include the total count in the response; false to exclude it. -// -// Returns: -// -// The updated Object with the "track_total_hits" parameter set. -func (o Object) TrackTotalHits(value bool) Object { - o["track_total_hits"] = value - return o -} - -// Size sets the "size" parameter in an es.Object. -// -// This method specifies the number of search results to return. It controls -// the maximum number of documents that will be included in the search response. -// This is useful for limiting the size of the result set, especially when dealing -// with large datasets or paginating results. -// -// Example usage: -// -// query := es.NewQuery(...).Size(10) -// // query now includes a "size" parameter with a value of 10, limiting results to 10 documents. -// -// Parameters: -// - size: An integer specifying the number of search results to return. -// Set this value to control the maximum number of documents in the response. -// -// Returns: -// -// The updated Object with the "size" parameter set. -func (o Object) Size(size int) Object { - o["size"] = size - return o -} - -// From sets the "from" parameter in an es.Object. -// -// This method specifies the starting point (offset) for the search results. -// It is used to skip a certain number of documents before starting to return -// the results. This is useful for pagination, allowing you to fetch results -// starting from a specific index. -// -// Example usage: -// -// query := es.NewQuery(...).From(20) -// // query now includes a "from" parameter with a value of 20, starting results from the 21st document. -// -// Parameters: -// - from: An integer specifying the starting point (offset) for the search results. -// Set this value to skip a certain number of documents before beginning the result set. -// -// Returns: -// -// The updated Object with the "from" parameter set. -func (o Object) From(from int) Object { - o["from"] = from - return o -} - -// SourceFalse sets the "_source" field to false in the es.Object. -// -// This method configures the es.Object to not include the source data in the search results. -// Setting the "_source" field to false excludes the entire source field from the response. -// -// Example usage: -// -// query := es.NewQuery(...).SourceFalse() -// // query now has a "_source" field set to false. -// -// Returns: -// -// The updated es.Object with the "_source" field set to false. -func (o Object) SourceFalse() Object { - o["_source"] = false - return o -} - -// SourceIncludes adds one or more fields to be included in the _source field of the es.Object. -// -// This method updates the _source field of the es.Object to specify which fields should be -// included in the search results. If the _source field or the "includes" key does not -// already exist, it initializes them appropriately before appending the new fields. -// -// Example usage: -// -// query := es.NewQuery(...).SourceIncludes("title", "author") -// // query now has a "_source" field with an "includes" key containing "title" and "author". -// -// Parameters: -// - fields: A variadic list of strings specifying the fields to be included. -// -// Returns: -// -// The updated Object with the "_source.includes" parameter set to the specified fields. -func (o Object) SourceIncludes(fields ...string) Object { - if len(fields) == 0 { - return o - } - source, ok := o["_source"].(Object) - if !ok { - source = Object{} - } - includes, ok := source["includes"].(Array) - if !ok { - includes = Array{} - } - for i := 0; i < len(fields); i++ { - includes = append(includes, fields[i]) - } - source["includes"] = includes - o["_source"] = source - return o -} - -// SourceExcludes adds one or more fields to be excluded from the _source field of the es.Object. -// -// This method updates the _source field of the es.Object to specify which fields should be -// excluded from the search results. If the _source field or the "excludes" key does not -// already exist, it initializes them appropriately before appending the new fields. -// -// Example usage: -// -// query := es.NewQuery(...).SourceExcludes("metadata", "private") -// // query now has a "_source" field with an "excludes" key containing "metadata" and "private". -// -// Parameters: -// - fields: A variadic list of strings specifying the fields to be excluded. -// -// Returns: -// -// The updated Object with the "_source.excludes" parameter set to the specified fields. -func (o Object) SourceExcludes(fields ...string) Object { - if len(fields) == 0 { - return o - } - source, ok := o["_source"].(Object) - if !ok { - source = Object{} - } - excludes, exists := source["excludes"].(Array) - if !exists { - excludes = Array{} - } - for i := 0; i < len(fields); i++ { - excludes = append(excludes, fields[i]) - } - source["excludes"] = excludes - o["_source"] = source - return o -} - -// Sort creates a new sortType object with the specified field. -// -// This function initializes a sortType object with a given field name. The -// field is used to specify the sorting criteria in the search query. The -// resulting sortType can be further configured with sorting order and mode. -// -// Example usage: -// -// s := Sort("age") -// // s now includes a sortType with an "age" field that can be further configured. -// -// Parameters: -// - field: A string representing the field to sort by. -// -// Returns: -// -// A sortType object with the specified field. -func Sort(field string) sortType { - return sortType{ - field: Object{}, - } -} - -func (s sortType) putInTheField(key string, value any) sortType { - for _, fieldObj := range s { - if fieldObject, ok := fieldObj.(Object); ok { - fieldObject[key] = value - break - } - } - return s -} - -// Order sets the "order" parameter in a sortType object. -// -// This method specifies the order in which the results should be sorted. -// It configures the sortType object to sort the results in ascending or -// descending order. -// -// Example usage: -// -// s := Sort("age").Order(Order.Desc) -// // s now includes an "order" parameter with the value "desc". -// -// Parameters: -// - order: An Order.Order value indicating the sorting order (e.g., ascending or descending). -// -// Returns: -// -// The updated sortType object with the "order" parameter set. -func (s sortType) Order(order Order.Order) sortType { - return s.putInTheField("order", order) -} - -// Mode sets the "mode" parameter in a sortType object. -// -// This method specifies the mode used for sorting the results. The mode -// determines how sorting should be handled, such as by specifying different -// tie-breaking strategies. -// -// Example usage: -// -// s := Sort("age").Mode(Mode.Avg) -// // s now includes a "mode" parameter with the value "avg". -// -// Parameters: -// - mode: A Mode.Mode value indicating the sorting mode (e.g., average, minimum, maximum). -// -// Returns: -// -// The updated sortType object with the "mode" parameter set. -func (s sortType) Mode(mode Mode.Mode) sortType { - return s.putInTheField("mode", mode) -} - -// Sort adds one or more sortType objects to an es.Object. -// -// This method allows you to specify multiple sorting criteria for the search query. -// Each sortType object defines how the results should be sorted based on different fields. -// -// Example usage: -// -// query := es.NewQuery(...).Sort(Sort("age").Order(Order.Desc), Sort("date").Order(Order.Asc)) -// // query now includes a "sort" parameter with multiple sortType objects. -// -// Parameters: -// - sorts: A variadic list of sortType objects, each specifying sorting criteria. -// -// Returns: -// -// The updated Object with the "sort" parameter set, containing the provided sortType objects. -func (o Object) Sort(sorts ...sortType) Object { - o["sort"] = sorts - return o -} diff --git a/es/base_query_test.go b/es/base_query_test.go deleted file mode 100644 index 847216a..0000000 --- a/es/base_query_test.go +++ /dev/null @@ -1,399 +0,0 @@ -package es_test - -import ( - "reflect" - "testing" - - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/test/assert" - - Mode "github.com/Trendyol/es-query-builder/es/enums/sort/mode" - Order "github.com/Trendyol/es-query-builder/es/enums/sort/order" -) - -//// NewQuery //// - -func Test_NewQuery_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.NewQuery) -} - -func Test_NewQuery_should_create_a_new_Object(t *testing.T) { - // Given When - bodyA := es.NewQuery(nil) - bodyB := es.NewQuery(nil) - - // Then - assert.NotNil(t, bodyA) - assert.NotNil(t, bodyB) - assert.Equal(t, bodyA, bodyB) - assert.NotEqualReference(t, bodyA, bodyB) - assert.MarshalWithoutError(t, bodyA) - assert.MarshalWithoutError(t, bodyB) -} - -func Test_NewQuery_should_return_type_of_Object(t *testing.T) { - // Given - query := es.NewQuery(nil) - - // When - bodyType := reflect.TypeOf(query).String() - - // Then - assert.NotNil(t, query) - assert.Equal(t, "es.Object", bodyType) - assert.MarshalWithoutError(t, query) -} - -func Test_NewQuery_should_add_query_field_into_Object(t *testing.T) { - // Given - query := es.NewQuery(nil) - - // When - q, exists := query["query"] - - // Then - assert.True(t, exists) - assert.NotNil(t, q) -} - -func Test_NewQuery_should_create_json_with_query_field(t *testing.T) { - // Given - query := es.NewQuery(nil) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{}}", bodyJSON) -} - -func Test_NewQuery_Bool_should_create_json_with_bool_field_inside_query(t *testing.T) { - // Given - query := es.NewQuery( - es.Bool(), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"bool\":{}}}", bodyJSON) -} - -//// TrackTotalHits //// - -func Test_Object_should_have_TrackTotalHits_method(t *testing.T) { - // Given - b := es.NewQuery(nil) - - // When Then - assert.NotNil(t, b.TrackTotalHits) -} - -func Test_TrackTotalHits_should_add_track_total_hits_field_into_Object(t *testing.T) { - // Given - query := es.NewQuery(nil) - - // When - _, beforeExists := query["track_total_hits"] - object := query.TrackTotalHits(true) - trackTotalHits, afterExists := query["track_total_hits"] - - // Then - assert.NotNil(t, object) - assert.False(t, beforeExists) - assert.True(t, afterExists) - assert.True(t, trackTotalHits.(bool)) -} - -//// Size //// - -func Test_Object_should_have_Size_method(t *testing.T) { - // Given - b := es.NewQuery(nil) - - // When Then - assert.NotNil(t, b.Size) -} - -func Test_Size_should_add_size_field_into_Object(t *testing.T) { - // Given - query := es.NewQuery(nil) - - // When - _, beforeExists := query["size"] - object := query.Size(123) - size, afterExists := query["size"] - - // Then - assert.NotNil(t, object) - assert.False(t, beforeExists) - assert.True(t, afterExists) - assert.Equal(t, 123, size.(int)) -} - -//// From //// - -func Test_Object_should_have_From_method(t *testing.T) { - // Given - b := es.NewQuery(nil) - - // When Then - assert.NotNil(t, b.From) -} - -func Test_From_should_add_from_field_into_Object(t *testing.T) { - // Given - query := es.NewQuery(nil) - - // When - _, beforeExists := query["from"] - object := query.From(1500) - from, afterExists := query["from"] - - // Then - assert.NotNil(t, object) - assert.False(t, beforeExists) - assert.True(t, afterExists) - assert.Equal(t, 1500, from.(int)) -} - -//// Sort //// - -func Test_Object_should_have_Sort_method(t *testing.T) { - // Given - b := es.NewQuery(nil) - - // When Then - assert.NotNil(t, b.Sort) -} - -func Test_Sort_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.Sort) -} - -func Test_Sort_should_return_sortType_with_order(t *testing.T) { - // Given - sort := es.Sort("name").Order(Order.Asc) - - // When - bodyType := reflect.TypeOf(sort).String() - - // Then - assert.NotNil(t, sort) - assert.Equal(t, "es.sortType", bodyType) - bodyJSON := assert.MarshalWithoutError(t, sort) - assert.Equal(t, "{\"name\":{\"order\":\"asc\"}}", bodyJSON) -} - -func Test_Sort_should_return_sortType_with_mode(t *testing.T) { - // Given - sort := es.Sort("age").Mode(Mode.Median) - - // When - bodyType := reflect.TypeOf(sort).String() - - // Then - assert.NotNil(t, sort) - assert.Equal(t, "es.sortType", bodyType) - bodyJSON := assert.MarshalWithoutError(t, sort) - assert.Equal(t, "{\"age\":{\"mode\":\"median\"}}", bodyJSON) -} - -func Test_Sort_should_return_sortType_with_order_and_mode(t *testing.T) { - // Given - sort := es.Sort("salary").Order(Order.Desc).Mode(Mode.Sum) - - // When - bodyType := reflect.TypeOf(sort).String() - - // Then - assert.NotNil(t, sort) - assert.Equal(t, "es.sortType", bodyType) - bodyJSON := assert.MarshalWithoutError(t, sort) - assert.Equal(t, "{\"salary\":{\"mode\":\"sum\",\"order\":\"desc\"}}", bodyJSON) -} - -func Test_Sort_should_add_sort_field_into_Object(t *testing.T) { - // Given - query := es.NewQuery(nil) - - // When - _, beforeExists := query["sort"] - query.Sort(es.Sort("name").Order(Order.Desc)) - sort, afterExists := query["sort"] - - // Then - assert.NotNil(t, sort) - assert.False(t, beforeExists) - assert.True(t, afterExists) - assert.IsTypeString(t, "[]es.sortType", sort) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{},\"sort\":[{\"name\":{\"order\":\"desc\"}}]}", bodyJSON) -} - -//// Source //// - -func Test_Object_should_have_SourceIncludes_method(t *testing.T) { - // Given - b := es.NewQuery(nil) - - // When Then - assert.NotNil(t, b.SourceIncludes()) -} - -func Test_SourceIncludes_should_add_source_field_with_includes_to_Object(t *testing.T) { - // Given - query := es.NewQuery(nil) - - // When - _, beforeExists := query["_source"] - query.SourceIncludes("test") - source, afterExists := query["_source"] - - // Then - assert.False(t, beforeExists) - assert.True(t, afterExists) - assert.NotNil(t, source) - assert.IsTypeString(t, "es.Object", source) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"_source\":{\"includes\":[\"test\"]},\"query\":{}}", bodyJSON) -} - -func Test_SourceIncludes_should_apped_includes_when_it_already_exists_in_the_source(t *testing.T) { - // Given - query := es.NewQuery(nil).SourceIncludes("first", "second") - - // When - _, beforeExists := query["_source"] - query. - SourceIncludes("third"). - SourceIncludes("fourth", "fifth") - source, afterExists := query["_source"] - - // Then - assert.True(t, beforeExists) - assert.True(t, afterExists) - assert.NotNil(t, source) - assert.IsTypeString(t, "es.Object", source) - bodyJSON := assert.MarshalWithoutError(t, query) - // nolint:golint,lll - assert.Equal(t, "{\"_source\":{\"includes\":[\"first\",\"second\",\"third\",\"fourth\",\"fifth\"]},\"query\":{}}", bodyJSON) -} - -func Test_SourceIncludes_should_not_add_includes_to_Object_when_fields_are_empty(t *testing.T) { - // Given - query := es.NewQuery(nil) - - // When - _, beforeExists := query["_source"] - query.SourceIncludes() // empty - source, afterExists := query["_source"] - - // Then - assert.False(t, beforeExists) - assert.False(t, afterExists) - assert.Nil(t, source) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{}}", bodyJSON) -} - -func Test_Object_should_have_SourceExcludes_method(t *testing.T) { - // Given - b := es.NewQuery(nil) - - // When Then - assert.NotNil(t, b.SourceExcludes()) -} - -func Test_SourceExcludes_should_add_source_field_with_excludes_to_Object(t *testing.T) { - // Given - query := es.NewQuery(nil) - - // When - _, beforeExists := query["_source"] - query.SourceExcludes("test") - source, afterExists := query["_source"] - - // Then - assert.False(t, beforeExists) - assert.True(t, afterExists) - assert.NotNil(t, source) - assert.IsTypeString(t, "es.Object", source) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"_source\":{\"excludes\":[\"test\"]},\"query\":{}}", bodyJSON) -} - -func Test_SourceExcludes_should_apped_excludes_when_it_already_exists_in_the_source(t *testing.T) { - // Given - query := es.NewQuery(nil).SourceExcludes("first", "second") - - // When - _, beforeExists := query["_source"] - query. - SourceExcludes("third"). - SourceExcludes("fourth", "fifth") - source, afterExists := query["_source"] - - // Then - assert.True(t, beforeExists) - assert.True(t, afterExists) - assert.NotNil(t, source) - assert.IsTypeString(t, "es.Object", source) - bodyJSON := assert.MarshalWithoutError(t, query) - // nolint:golint,lll - assert.Equal(t, "{\"_source\":{\"excludes\":[\"first\",\"second\",\"third\",\"fourth\",\"fifth\"]},\"query\":{}}", bodyJSON) -} - -func Test_SourceExcludes_should_not_add_excludes_to_Object_when_fields_are_empty(t *testing.T) { - // Given - query := es.NewQuery(nil) - - // When - _, beforeExists := query["_source"] - query.SourceExcludes() // empty - source, afterExists := query["_source"] - - // Then - assert.False(t, beforeExists) - assert.False(t, afterExists) - assert.Nil(t, source) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{}}", bodyJSON) -} - -func Test_Object_should_have_SourceFalse_method(t *testing.T) { - // Given - b := es.NewQuery(nil) - - // When Then - assert.NotNil(t, b.SourceFalse) -} - -func Test_SourceFalse_should_set_source_field_as_false(t *testing.T) { - // Given - query := es.NewQuery(nil) - - // When - _, beforeExists := query["_source"] - query.SourceFalse() - source, afterExists := query["_source"] - - // Then - assert.NotNil(t, source) - assert.False(t, beforeExists) - assert.True(t, afterExists) - assert.False(t, source.(bool)) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"_source\":false,\"query\":{}}", bodyJSON) -} - -//// Aggs //// - -func Test_Object_should_have_Aggs_method(t *testing.T) { - // Given - b := es.NewQuery(nil) - - // When Then - assert.NotNil(t, b.Aggs) -} diff --git a/es/bool_query.go b/es/bool_query.go deleted file mode 100644 index 0e33c74..0000000 --- a/es/bool_query.go +++ /dev/null @@ -1,241 +0,0 @@ -package es - -type BoolType Object - -type FilterType Array - -type MustType Array - -type MustNotType Array - -type ShouldType Array - -// Bool creates and returns an empty BoolType object. -// -// This function is typically used to initialize a BoolType, which can be -// populated later with the appropriate boolean query conditions. -// -// Example usage: -// -// b := Bool() -// // b is now an empty BoolType object that can be used in a query. -// -// Returns: -// -// An empty BoolType object. -func Bool() BoolType { - return BoolType{} -} - -// MinimumShouldMatch sets the "minimum_should_match" parameter in a BoolType query. -// -// This method allows you to specify the minimum number of "should" clauses -// that must match in a boolean query. The "minimum_should_match" parameter -// is often used to fine-tune the results of a boolean query by requiring a -// certain number of optional (should) clauses to match. -// -// Example usage: -// -// b := Bool().MinimumShouldMatch(2) -// // b now includes a "minimum_should_match" parameter with a value of 2. -// -// Parameters: -// - minimumShouldMatch: An integer specifying the minimum number of "should" -// clauses that must match for a document to be considered a match. -// -// Returns: -// -// The updated BoolType object with the "minimum_should_match" parameter set. -func (b BoolType) MinimumShouldMatch(minimumShouldMatch any) BoolType { - b["minimum_should_match"] = minimumShouldMatch - return b -} - -// AdjustPureNegative sets the "adjust_pure_negative" parameter in a BoolType query. -// -// This method allows you to specify whether pure negative queries should be -// adjusted or not. When set to true, the query will be adjusted to include -// pure negative queries, which can influence the matching behavior of the -// boolean query. -// -// Example usage: -// -// b := Bool().AdjustPureNegative(true) -// // b now includes an "adjust_pure_negative" parameter set to true. -// -// Parameters: -// - adjustPureNegative: A boolean value indicating whether to adjust -// pure negative queries in the boolean query. -// -// Returns: -// -// The updated BoolType object with the "adjust_pure_negative" parameter set. -func (b BoolType) AdjustPureNegative(adjustPureNegative bool) BoolType { - b["adjust_pure_negative"] = adjustPureNegative - return b -} - -// Boost sets the "boost" parameter in a BoolType query. -// -// This method allows you to assign a boost value to a boolean query, which -// can be used to increase or decrease the relevance score of the query's -// results. The boost parameter is a multiplier that influences how strongly -// this particular query should be considered compared to others. -// -// Example usage: -// -// b := Bool().Boost(1.5) -// // b now includes a "boost" parameter with a value of 1.5. -// -// Parameters: -// - boost: A floating-point number representing the boost factor. Higher -// values increase the importance of the query in scoring, while lower -// values decrease it. -// -// Returns: -// -// The updated BoolType object with the "boost" parameter set. -func (b BoolType) Boost(boost float64) BoolType { - b["boost"] = boost - return b -} - -// Filter adds one or more filter conditions to the BoolType object. -// -// This method updates the "filter" section of the BoolType object by appending -// the specified filter conditions. It accepts a variadic number of filter conditions, -// checks their types, and adds them to the "filter" array in the BoolType object. -// -// Example usage: -// -// b := es.Bool(). -// Filter( -// es.Term("title", "es-query-builder"), -// es.Exists("filter"), -// ) -// // b now contains the provided conditions in the "filter" array. -// -// Parameters: -// - items: A variadic list of filter conditions to be added. The type is generic. -// -// Returns: -// -// The updated BoolType object with the new filter conditions added. -func (b BoolType) Filter(items ...any) BoolType { - filter, ok := b["filter"].(FilterType) - if !ok { - filter = FilterType{} - } - for i := 0; i < len(items); i++ { - if field, fOk := correctType(items[i]); fOk { - filter = append(filter, field) - } - } - b["filter"] = filter - return b -} - -// Must adds one or more conditions to the "must" section of the BoolType object. -// -// This method updates the "must" section by appending the specified conditions. -// It accepts a variadic number of conditions, checks their types, and adds them to -// the "must" array in the BoolType object. -// -// Example usage: -// -// b := es.Bool(). -// Must( -// es.Term("title", "es-query-builder"), -// es.Exists("must"), -// ) -// // b now contains the provided conditions in the "must" array. -// -// Parameters: -// - items: A variadic list of conditions to be added. The type is generic. -// -// Returns: -// -// The updated BoolType object with the new conditions added to the "must" section. -func (b BoolType) Must(items ...any) BoolType { - must, ok := b["must"].(MustType) - if !ok { - must = MustType{} - } - for i := 0; i < len(items); i++ { - if field, fOk := correctType(items[i]); fOk { - must = append(must, field) - } - } - b["must"] = must - return b -} - -// MustNot adds one or more conditions to the "must_not" section of the BoolType object. -// -// This method updates the "must_not" section by appending the specified conditions. -// It accepts a variadic number of conditions, checks their types, and adds them to -// the "must_not" array in the BoolType object. -// -// Example usage: -// -// b := es.Bool(). -// MustNot( -// es.Term("title", "es-query-builder"), -// es.Exists("mustNot"), -// ) -// // b now contains the provided conditions in the "must_not" array. -// -// Parameters: -// - items: A variadic list of conditions to be added. The type is generic. -// -// Returns: -// -// The updated BoolType object with the new conditions added to the "must_not" section. -func (b BoolType) MustNot(items ...any) BoolType { - mustNot, ok := b["must_not"].(MustNotType) - if !ok { - mustNot = MustNotType{} - } - for i := 0; i < len(items); i++ { - if field, fOk := correctType(items[i]); fOk { - mustNot = append(mustNot, field) - } - } - b["must_not"] = mustNot - return b -} - -// Should adds one or more conditions to the "should" section of the BoolType object. -// -// This method updates the "should" section by appending the specified conditions. -// It accepts a variadic number of conditions, checks their types, and adds them to -// the "should" array in the BoolType object. -// -// Example usage: -// -// b := es.Bool(). -// Should( -// es.Term("title", "es-query-builder"), -// es.Exists("should"), -// ) -// // b now contains the provided conditions in the "should" array. -// -// Parameters: -// - items: A variadic list of conditions to be added. The type is generic. -// -// Returns: -// -// The updated BoolType object with the new conditions added to the "should" section. -func (b BoolType) Should(items ...any) BoolType { - should, ok := b["should"].(ShouldType) - if !ok { - should = ShouldType{} - } - for i := 0; i < len(items); i++ { - if field, fOk := correctType(items[i]); fOk { - should = append(should, field) - } - } - b["should"] = should - return b -} diff --git a/es/bool_query_test.go b/es/bool_query_test.go deleted file mode 100644 index b45e27c..0000000 --- a/es/bool_query_test.go +++ /dev/null @@ -1,320 +0,0 @@ -package es_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/test/assert" -) - -//// Bool //// - -func Test_Bool_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.Bool) -} - -func Test_Bool_method_should_create_boolType(t *testing.T) { - // Given - b := es.Bool() - - // Then - assert.NotNil(t, b) - assert.IsTypeString(t, "es.BoolType", b) -} - -func Test_Bool_should_have_MinimumShouldMatch_method(t *testing.T) { - // Given - b := es.Bool() - - // When Then - assert.NotNil(t, b.MinimumShouldMatch) -} - -func Test_Bool_MinimumShouldMatch_should_create_json_with_int_minimum_should_match_field_inside_bool(t *testing.T) { - // Given - query := es.NewQuery( - es.Bool(). - MinimumShouldMatch(7), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"bool\":{\"minimum_should_match\":7}}}", bodyJSON) -} - -func Test_Bool_MinimumShouldMatch_should_create_json_with_string_minimum_should_match_field_inside_bool(t *testing.T) { - // Given - query := es.NewQuery( - es.Bool(). - MinimumShouldMatch("2<-25% 9<-3"), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"bool\":{\"minimum_should_match\":\"2\\u003c-25% 9\\u003c-3\"}}}", bodyJSON) -} - -func Test_Bool_should_have_AdjustPureNegative_method(t *testing.T) { - // Given - b := es.Bool() - - // When Then - assert.NotNil(t, b.AdjustPureNegative) -} - -func Test_Bool_AdjustPureNegative_should_create_json_with_adjust_pure_negative_field_inside_bool(t *testing.T) { - // Given - query := es.NewQuery( - es.Bool(). - AdjustPureNegative(false), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"bool\":{\"adjust_pure_negative\":false}}}", bodyJSON) -} - -func Test_Bool_should_have_Boost_method(t *testing.T) { - // Given - b := es.Bool() - - // When Then - assert.NotNil(t, b.Boost) -} - -func Test_Bool_Boost_should_create_json_with_minimum_should_match_field_inside_bool(t *testing.T) { - // Given - query := es.NewQuery( - es.Bool(). - Boost(3.1415), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"bool\":{\"boost\":3.1415}}}", bodyJSON) -} - -func Test_Bool_should_have_Filter_method(t *testing.T) { - // Given - b := es.Bool() - - // When Then - assert.NotNil(t, b.Filter) -} - -func Test_Bool_should_have_Must_method(t *testing.T) { - // Given - b := es.Bool() - - // When Then - assert.NotNil(t, b.Must) -} - -func Test_Bool_should_have_MustNot_method(t *testing.T) { - // Given - b := es.Bool() - - // When Then - assert.NotNil(t, b.MustNot) -} - -func Test_Bool_should_have_Should_method(t *testing.T) { - // Given - b := es.Bool() - - // When Then - assert.NotNil(t, b.Should) -} - -//// Bool.Filter //// - -func Test_Filter_method_should_return_boolType(t *testing.T) { - // Given - b := es.Bool() - - // When - filter := b.Filter() - - // Then - assert.NotNil(t, filter) - assert.IsTypeString(t, "es.BoolType", filter) -} - -func Test_Filter_method_should_add_filter_if_doesnt_exist_before(t *testing.T) { - // Given - b := es.Bool() - - // When - _, beforeExists := b["filter"] - filter := b.Filter() - _, afterExists := b["filter"] - - // Then - assert.NotNil(t, filter) - assert.False(t, beforeExists) - assert.True(t, afterExists) -} - -func Test_Filter_method_should_hold_items(t *testing.T) { - // Given - b := es.Bool(). - Filter( - es.Term("id", 12345), - ) - - // When - filter, exists := b["filter"] - - // Then - assert.True(t, exists) - assert.IsTypeString(t, "es.FilterType", filter) - - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"filter\":[{\"term\":{\"id\":{\"value\":12345}}}]}", bodyJSON) -} - -//// Bool.Must //// - -func Test_Must_method_should_return_boolType(t *testing.T) { - // Given - b := es.Bool() - - // When - must := b.Must() - - // Then - assert.NotNil(t, must) - assert.IsTypeString(t, "es.BoolType", must) -} - -func Test_Must_method_should_add_must_if_doesnt_exist_before(t *testing.T) { - // Given - b := es.Bool() - - // When - _, beforeExists := b["must"] - filter := b.Must() - _, afterExists := b["must"] - - // Then - assert.NotNil(t, filter) - assert.False(t, beforeExists) - assert.True(t, afterExists) -} - -func Test_Must_method_should_hold_items(t *testing.T) { - // Given - b := es.Bool(). - Must( - es.Term("id", 12345), - ) - - // When - must, exists := b["must"] - - // Then - assert.True(t, exists) - assert.IsTypeString(t, "es.MustType", must) - - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"must\":[{\"term\":{\"id\":{\"value\":12345}}}]}", bodyJSON) -} - -//// Bool.MustNot //// - -func Test_MustNot_method_should_return_boolType(t *testing.T) { - // Given - b := es.Bool() - - // When - mustNot := b.MustNot() - - // Then - assert.NotNil(t, mustNot) - assert.IsTypeString(t, "es.BoolType", mustNot) -} - -func Test_MustNot_method_should_add_must_not_if_doesnt_exist_before(t *testing.T) { - // Given - b := es.Bool() - - // When - _, beforeExists := b["must_not"] - filter := b.MustNot() - _, afterExists := b["must_not"] - - // Then - assert.NotNil(t, filter) - assert.False(t, beforeExists) - assert.True(t, afterExists) -} - -func Test_MustNot_method_should_hold_items(t *testing.T) { - // Given - b := es.Bool(). - MustNot( - es.Term("id", 12345), - ) - - // When - mustNot, exists := b["must_not"] - - // Then - assert.True(t, exists) - assert.IsTypeString(t, "es.MustNotType", mustNot) - - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"must_not\":[{\"term\":{\"id\":{\"value\":12345}}}]}", bodyJSON) -} - -//// Bool.Should //// - -func Test_Should_method_should_return_boolType(t *testing.T) { - // Given - b := es.Bool() - - // When - should := b.Should() - - // Then - assert.NotNil(t, should) - assert.IsTypeString(t, "es.BoolType", should) -} - -func Test_Should_method_should_add_should_if_doesnt_exist_before(t *testing.T) { - // Given - b := es.Bool() - - // When - _, beforeExists := b["should"] - filter := b.Should() - _, afterExists := b["should"] - - // Then - assert.NotNil(t, filter) - assert.False(t, beforeExists) - assert.True(t, afterExists) -} - -func Test_Should_method_should_hold_items(t *testing.T) { - // Given - b := es.Bool(). - Should( - es.Term("id", 12345), - ) - - // When - should, exists := b["should"] - - // Then - assert.True(t, exists) - assert.IsTypeString(t, "es.ShouldType", should) - - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"should\":[{\"term\":{\"id\":{\"value\":12345}}}]}", bodyJSON) -} diff --git a/es/condition/if.go b/es/condition/if.go deleted file mode 100644 index 2c6410d..0000000 --- a/es/condition/if.go +++ /dev/null @@ -1,25 +0,0 @@ -package condition - -// If returns the provided `item` if `condition` is true; otherwise, it returns nil. -// This function is generic and operates on maps with string keys or slices of any type. -// -// Parameters: -// - item: The map or slice to potentially return if the condition is met. -// - condition: A boolean that determines if `item` should be returned. -// -// Returns: -// - The original `item` (map or slice) if `condition` is true, otherwise nil. -// -// Example usage: -// -// result := If(es.Object{"key": "value"}, true) -// // result is es.Object{"key": "value"} -// -// result = If(es.Object{"key": "value"}, false) -// // result is nil -func If[T ~map[string]any | ~[]any](item T, condition bool) T { - if !condition { - return nil - } - return item -} diff --git a/es/condition/if_test.go b/es/condition/if_test.go deleted file mode 100644 index 9a2c9ae..0000000 --- a/es/condition/if_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package condition_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/es/condition" - "github.com/Trendyol/es-query-builder/test/assert" -) - -func Test_Condition_If_should_add_Term_When_condition_is_true(t *testing.T) { - // Given - cond := true - - // When - query := es.NewQuery( - es.Bool(). - Filter( - condition.If(es.Term("language", "en"), cond), - es.Exists("brandId"), - ), - ) - - // Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - // nolint:golint,lll - assert.Equal(t, "{\"query\":{\"bool\":{\"filter\":[{\"term\":{\"language\":{\"value\":\"en\"}}},{\"exists\":{\"field\":\"brandId\"}}]}}}", bodyJSON) -} - -func Test_Condition_If_should_not_add_Term_When_condition_is_not_true(t *testing.T) { - // Given - cond := false - - // When - query := es.NewQuery( - es.Bool(). - Filter( - condition.If(es.Term("language", "en"), cond), - es.Exists("brandId"), - ), - ) - - // Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"bool\":{\"filter\":[{\"exists\":{\"field\":\"brandId\"}}]}}}", bodyJSON) -} - -func Test_Condition_If_should_work_with_slices(t *testing.T) { - // Given - cond := true - - // When - result := condition.If(es.Array{1, 2, 3, 4}, cond) - - // Then - assert.NotNil(t, result) - bodyJSON := assert.MarshalWithoutError(t, result) - assert.Equal(t, "[1,2,3,4]", bodyJSON) -} diff --git a/es/enums/match/operator/operator.go b/es/enums/match/operator/operator.go deleted file mode 100644 index ea4f10a..0000000 --- a/es/enums/match/operator/operator.go +++ /dev/null @@ -1,32 +0,0 @@ -package operator - -// Operator sets the "operator" field in the matchType object. -// -// This method specifies the logical operator used to combine multiple match conditions. -// It updates the matchType object to include the provided operator for query matching. -// -// Example usage: -// -// match := es.Match("field", "value").Operator(Operator.And) -// // match now has the "operator" field set to "and" in the matchType object. -// -// Parameters: -// - operator: An Operator value representing the logical operator to use for combining match conditions. -// It can be either Operator.Or or Operator.And. -// -// Returns: -// -// The updated matchType object with the "operator" field set to the specified operator. -type Operator string - -const ( - // Or indicates that conditions should be combined with a logical OR. - Or Operator = "or" - - // And indicates that conditions should be combined with a logical AND. - And Operator = "and" -) - -func (operator Operator) String() string { - return string(operator) -} diff --git a/es/enums/match/operator/operator_test.go b/es/enums/match/operator/operator_test.go deleted file mode 100644 index 521d10c..0000000 --- a/es/enums/match/operator/operator_test.go +++ /dev/null @@ -1,25 +0,0 @@ -package operator_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/test/assert" - - Operator "github.com/Trendyol/es-query-builder/es/enums/match/operator" -) - -func Test_OperatorString(t *testing.T) { - tests := []struct { - operator Operator.Operator - result string - }{ - {Operator.And, "and"}, - {Operator.Or, "or"}, - } - - for _, test := range tests { - t.Run(test.result, func(t *testing.T) { - assert.Equal(t, test.result, test.operator.String()) - }) - } -} diff --git a/es/enums/match/zero-terms-query/zero_terms_query.go b/es/enums/match/zero-terms-query/zero_terms_query.go deleted file mode 100644 index 2cfeed3..0000000 --- a/es/enums/match/zero-terms-query/zero_terms_query.go +++ /dev/null @@ -1,33 +0,0 @@ -package zerotermsquery - -// ZeroTermsQuery sets the "zero_terms_query" field in the matchType object. -// -// This method specifies the behavior of the match query when no terms remain after analysis, -// such as when all terms are stop words. It updates the matchType object to include the provided -// zeroTermsQuery value, which determines how the query should respond in this scenario. -// -// Example usage: -// -// match := es.Match("field", "value").ZeroTermsQuery(ZeroTermsQuery.All) -// // match now has the "zero_terms_query" field set to "all" in the matchType object. -// -// Parameters: -// - zeroTermsQuery: A ZeroTermsQuery value indicating the behavior for zero-term queries. -// It can be either ZeroTermsQuery.All or ZeroTermsQuery.None. -// -// Returns: -// -// The updated matchType object with the "zero_terms_query" field set to the specified value. -type ZeroTermsQuery string - -const ( - // All indicates that all documents should be matched when no terms remain. - All ZeroTermsQuery = "all" - - // None indicates that no documents should be matched when no terms remain. - None ZeroTermsQuery = "none" -) - -func (zeroTermsQuery ZeroTermsQuery) String() string { - return string(zeroTermsQuery) -} diff --git a/es/enums/match/zero-terms-query/zero_terms_query_test.go b/es/enums/match/zero-terms-query/zero_terms_query_test.go deleted file mode 100644 index 2c65449..0000000 --- a/es/enums/match/zero-terms-query/zero_terms_query_test.go +++ /dev/null @@ -1,25 +0,0 @@ -package zerotermsquery_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/test/assert" - - ZeroTermsQuery "github.com/Trendyol/es-query-builder/es/enums/match/zero-terms-query" -) - -func Test_ZeroTermsQueryString(t *testing.T) { - tests := []struct { - zeroTermsQuery ZeroTermsQuery.ZeroTermsQuery - result string - }{ - {ZeroTermsQuery.All, "all"}, - {ZeroTermsQuery.None, "none"}, - } - - for _, test := range tests { - t.Run(test.result, func(t *testing.T) { - assert.Equal(t, test.result, test.zeroTermsQuery.String()) - }) - } -} diff --git a/es/enums/nested/score-mode/score_mode.go b/es/enums/nested/score-mode/score_mode.go deleted file mode 100644 index 8bb9dc7..0000000 --- a/es/enums/nested/score-mode/score_mode.go +++ /dev/null @@ -1,42 +0,0 @@ -package scoremode - -// ScoreMode represents the different scoring modes for nested queries. -// -// ScoreMode is a string type used to specify how scores should be calculated and -// combined for nested queries in search queries. It provides various options for -// aggregating scores of nested documents. -// -// Example usage: -// -// var mode ScoreMode = Sum -// -// // Use mode in a nested query configuration -// -// Constants: -// - Avg: Average score of the nested documents. -// - Max: Maximum score of the nested documents. -// - Min: Minimum score of the nested documents. -// - None: No scoring for the nested documents. -// - Sum: Sum of the scores of the nested documents. -type ScoreMode string - -const ( - // Avg indicates that the average score of nested documents should be used. - Avg ScoreMode = "avg" - - // Max indicates that the maximum score among nested documents should be used. - Max ScoreMode = "max" - - // Min indicates that the minimum score among nested documents should be used. - Min ScoreMode = "min" - - // None indicates that no scoring should be applied to nested documents. - None ScoreMode = "none" - - // Sum indicates that the sum of the scores of nested documents should be used. - Sum ScoreMode = "sum" -) - -func (scoreMode ScoreMode) String() string { - return string(scoreMode) -} diff --git a/es/enums/nested/score-mode/score_mode_test.go b/es/enums/nested/score-mode/score_mode_test.go deleted file mode 100644 index c28c853..0000000 --- a/es/enums/nested/score-mode/score_mode_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package scoremode_test - -import ( - "testing" - - scoremode "github.com/Trendyol/es-query-builder/es/enums/nested/score-mode" - "github.com/Trendyol/es-query-builder/test/assert" -) - -func Test_ScoreModeString(t *testing.T) { - tests := []struct { - mode scoremode.ScoreMode - result string - }{ - {scoremode.Avg, "avg"}, - {scoremode.Max, "max"}, - {scoremode.Min, "min"}, - {scoremode.None, "none"}, - {scoremode.Sum, "sum"}, - } - - for _, test := range tests { - t.Run(test.result, func(t *testing.T) { - assert.Equal(t, test.result, test.mode.String()) - }) - } -} diff --git a/es/enums/sort/mode/mode.go b/es/enums/sort/mode/mode.go deleted file mode 100644 index 82ea205..0000000 --- a/es/enums/sort/mode/mode.go +++ /dev/null @@ -1,45 +0,0 @@ -package mode - -// Mode represents various aggregation modes for queries or operations. -// -// Mode is a string type used to specify different ways to aggregate or process -// values in queries. It provides various options for combining or analyzing data. -// -// Example usage: -// -// var mode Mode = Sum -// -// // Use mode in a query or operation configuration -// -// Constants: -// - Min: Minimum value from the set of values. -// - Max: Maximum value from the set of values. -// - Sum: Sum of all values in the set. -// - Avg: Average of all values in the set. -// - Median: Median value from the set of values. -// - Default: The default aggregation mode, typically used as a fallback. -type Mode string - -const ( - // Min indicates that the minimum value from the set should be used. - Min Mode = "min" - - // Max indicates that the maximum value from the set should be used. - Max Mode = "max" - - // Sum indicates that the sum of all values in the set should be used. - Sum Mode = "sum" - - // Avg indicates that the average of all values in the set should be used. - Avg Mode = "avg" - - // Median indicates that the median value from the set should be used. - Median Mode = "median" - - // Default indicates the default aggregation mode, used as a fallback or if no specific mode is provided. - Default Mode = "_default" -) - -func (mode Mode) String() string { - return string(mode) -} diff --git a/es/enums/sort/mode/mode_test.go b/es/enums/sort/mode/mode_test.go deleted file mode 100644 index 570deb7..0000000 --- a/es/enums/sort/mode/mode_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package mode_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/test/assert" - - Mode "github.com/Trendyol/es-query-builder/es/enums/sort/mode" -) - -func Test_ModeString(t *testing.T) { - tests := []struct { - mode Mode.Mode - result string - }{ - {Mode.Min, "min"}, - {Mode.Max, "max"}, - {Mode.Sum, "sum"}, - {Mode.Avg, "avg"}, - {Mode.Median, "median"}, - {Mode.Default, "_default"}, - } - - for _, test := range tests { - t.Run(test.result, func(t *testing.T) { - assert.Equal(t, test.result, test.mode.String()) - }) - } -} diff --git a/es/enums/sort/order/order.go b/es/enums/sort/order/order.go deleted file mode 100644 index 4cce5ac..0000000 --- a/es/enums/sort/order/order.go +++ /dev/null @@ -1,34 +0,0 @@ -package order - -// Order represents the sorting order for queries or operations. -// -// Order is a string type used to specify the direction of sorting or ordering -// for query results or data operations. It provides options for ascending or -// descending order, as well as a default sorting option. -// -// Example usage: -// -// var order Order = Asc -// -// // Use order in a query or operation configuration -// -// Constants: -// - Asc: Ascending order for sorting or ordering. -// - Desc: Descending order for sorting or ordering. -// - Default: The default sorting order, typically used as a fallback. -type Order string - -const ( - // Asc indicates that the results should be sorted in ascending order. - Asc Order = "asc" - - // Desc indicates that the results should be sorted in descending order. - Desc Order = "desc" - - // Default indicates the default sorting order, used as a fallback or if no specific order is provided. - Default Order = "_default" -) - -func (order Order) String() string { - return string(order) -} diff --git a/es/enums/sort/order/order_test.go b/es/enums/sort/order/order_test.go deleted file mode 100644 index 4f39ea8..0000000 --- a/es/enums/sort/order/order_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package order_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/test/assert" - - Order "github.com/Trendyol/es-query-builder/es/enums/sort/order" -) - -func TestOrderString(t *testing.T) { - tests := []struct { - mode Order.Order - result string - }{ - {Order.Asc, "asc"}, - {Order.Desc, "desc"}, - {Order.Default, "_default"}, - } - - for _, test := range tests { - t.Run(test.result, func(t *testing.T) { - assert.Equal(t, test.result, test.mode.String()) - }) - } -} diff --git a/es/exists_query.go b/es/exists_query.go deleted file mode 100644 index 87765dd..0000000 --- a/es/exists_query.go +++ /dev/null @@ -1,80 +0,0 @@ -package es - -type existsType Object - -// Exists creates a new existsType object to check if a field exists. -// -// This function initializes an existsType object that specifies a query to check -// if a particular field exists in the documents. The key parameter represents -// the name of the field to check for existence. -// -// Example usage: -// -// e := Exists("title") -// // e now contains an existsType object that checks for the existence of the "title" field. -// -// Parameters: -// - key: A string representing the name of the field to check for existence. -// -// Returns: -// -// An existsType object that includes the "exists" query for the specified field. -func Exists(key string) existsType { - return existsType{ - "exists": Object{ - "field": key, - }, - } -} - -// ExistsFunc creates an existsType object based on a condition evaluated by a function. -// -// This function conditionally creates an existsType object if the provided function -// returns true for the given key. If the function returns false, it returns nil -// instead of creating an existsType object. -// -// Example usage: -// -// e := ExistsFunc("title", func(key string) bool { -// return key != "" -// }) -// // e is either an existsType object or nil based on the condition. -// -// Parameters: -// - key: A string representing the name of the field to check for existence. -// - f: A function that takes a key and returns a boolean indicating whether -// to create the existsType object. -// -// Returns: -// -// An existsType object if the condition is true; otherwise, nil. -func ExistsFunc(key string, f func(key string) bool) existsType { - if !f(key) { - return nil - } - return Exists(key) -} - -// ExistsIf creates an existsType object based on a boolean condition. -// -// This function creates an existsType object if the provided condition is true. -// If the condition is false, it returns nil instead of creating an existsType object. -// -// Example usage: -// -// e := ExistsIf("title", true) -// // e is an existsType object if the condition is true; otherwise, it is nil. -// -// Parameters: -// - key: A string representing the name of the field to check for existence. -// - condition: A boolean value that determines whether to create the existsType object. -// -// Returns: -// -// An existsType object if the condition is true; otherwise, nil. -func ExistsIf(key string, condition bool) existsType { - if !condition { - return nil - } - return Exists(key) -} diff --git a/es/exists_query_test.go b/es/exists_query_test.go deleted file mode 100644 index 036b1c9..0000000 --- a/es/exists_query_test.go +++ /dev/null @@ -1,164 +0,0 @@ -package es_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/test/assert" -) - -//// Exists //// - -func Test_Exists_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.Exists) -} - -func Test_Exists_should_create_json_with_exists_field_inside_query(t *testing.T) { - // Given - query := es.NewQuery( - es.Exists("key"), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"exists\":{\"field\":\"key\"}}}", bodyJSON) -} - -func Test_Exists_method_should_create_existsType(t *testing.T) { - // Given - b := es.Exists("key") - - // Then - assert.NotNil(t, b) - assert.IsTypeString(t, "es.existsType", b) -} - -//// ExistsFunc //// - -func Test_ExistsFunc_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.ExistsFunc) -} - -func Test_ExistsFunc_should_create_json_with_exists_field_inside_query(t *testing.T) { - // Given - query := es.NewQuery( - es.ExistsFunc("key", func(key string) bool { - return true - }), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"exists\":{\"field\":\"key\"}}}", bodyJSON) -} - -func Test_ExistsFunc_should_not_add_exists_field_inside_query_when_callback_result_is_false(t *testing.T) { - // Given - query := es.NewQuery( - es.ExistsFunc("key", func(key string) bool { - return false - }), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{}}", bodyJSON) -} - -func Test_ExistsFunc_should_add_only_exists_fields_inside_the_query_when_callback_result_is_true(t *testing.T) { - // Given - query := es.NewQuery( - es.Bool(). - Filter( - es.ExistsFunc("a", func(key string) bool { - return false - }), - es.ExistsFunc("c", func(key string) bool { - return true - }), - es.ExistsFunc("e", func(key string) bool { - return true - }), - ), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"bool\":{\"filter\":[{\"exists\":{\"field\":\"c\"}},{\"exists\":{\"field\":\"e\"}}]}}}", bodyJSON) -} - -func Test_ExistsFunc_method_should_create_existsType(t *testing.T) { - // Given - b := es.ExistsFunc("key", func(key string) bool { - return true - }) - - // Then - assert.NotNil(t, b) - assert.IsTypeString(t, "es.existsType", b) -} - -//// ExistsIF //// - -func Test_ExistsIf_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.ExistsIf) -} - -func Test_ExistsIf_should_create_json_with_exists_field_inside_query(t *testing.T) { - // Given - query := es.NewQuery( - es.ExistsIf("key", true), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"exists\":{\"field\":\"key\"}}}", bodyJSON) -} - -func Test_ExistsIf_should_not_add_exists_field_inside_query_when_condition_is_false(t *testing.T) { - // Given - query := es.NewQuery( - es.ExistsIf("key", false), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{}}", bodyJSON) -} - -func Test_ExistsIf_should_add_only_exists_fields_inside_the_query_when_condition_is_true(t *testing.T) { - // Given - query := es.NewQuery( - es.Bool(). - Filter( - es.ExistsIf("a", false), - es.ExistsIf("c", true), - es.ExistsIf("e", true), - ), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"bool\":{\"filter\":[{\"exists\":{\"field\":\"c\"}},{\"exists\":{\"field\":\"e\"}}]}}}", bodyJSON) -} - -func Test_ExistsIf_method_should_create_existsType(t *testing.T) { - // Given - b := es.ExistsFunc("key", func(key string) bool { - return true - }) - - // Then - assert.NotNil(t, b) - assert.IsTypeString(t, "es.existsType", b) -} diff --git a/es/match_all_query.go b/es/match_all_query.go deleted file mode 100644 index c104b8b..0000000 --- a/es/match_all_query.go +++ /dev/null @@ -1,50 +0,0 @@ -package es - -type matchAllType Object - -// MatchAll creates a new matchAllType object that matches all documents. -// -// This function initializes a matchAllType object that is used to construct queries -// that match all documents. This can be useful for scenarios where you want to ensure -// that all documents are included in the results. -// -// Example usage: -// -// ma := MatchAll() -// // ma now contains a matchAllType object that matches all documents. -// -// Returns: -// -// A matchAllType object with a match_all query that matches all documents. -func MatchAll() matchAllType { - return matchAllType{ - "match_all": Object{}, - } -} - -func (m matchAllType) putInTheField(key string, value any) matchAllType { - if matchAll, ok := m["match_all"].(Object); ok { - matchAll[key] = value - } - return m -} - -// Boost sets the "boost" field in the match_all query. -// -// This method configures the match_all query to use a specified boost factor, which influences -// the relevance scoring of the matched documents. -// -// Example usage: -// -// ma := MatchAll().Boost(1.5) -// // ma now has a "boost" field set to 1.5 in the match_all query object. -// -// Parameters: -// - boost: A float64 value representing the boost factor to be applied to the match_all query. -// -// Returns: -// -// The updated matchAllType object with the "boost" field set to the specified value. -func (m matchAllType) Boost(boost float64) matchAllType { - return m.putInTheField("boost", boost) -} diff --git a/es/match_all_query_test.go b/es/match_all_query_test.go deleted file mode 100644 index 2c677dc..0000000 --- a/es/match_all_query_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package es_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/test/assert" -) - -//// MatchAll //// - -func Test_MatchAll_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.MatchAll) -} - -func Test_MatchAll_method_should_create_matchAllType(t *testing.T) { - // Given - b := es.MatchAll() - - // Then - assert.NotNil(t, b) - assert.IsTypeString(t, "es.matchAllType", b) -} - -func Test_MatchAll_should_create_json_with_match_all_field_inside_query(t *testing.T) { - // Given - query := es.NewQuery( - es.MatchAll(). - Boost(2.14), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"match_all\":{\"boost\":2.14}}}", bodyJSON) -} diff --git a/es/match_none_query.go b/es/match_none_query.go deleted file mode 100644 index ec4cd38..0000000 --- a/es/match_none_query.go +++ /dev/null @@ -1,87 +0,0 @@ -package es - -import Operator "github.com/Trendyol/es-query-builder/es/enums/match/operator" - -type matchNoneType Object - -// MatchNone creates a new matchNoneType object with the specified field and query. -// -// This function initializes a matchNoneType object for a match_none query, where the key -// represents the field name and query is the value to be matched. This is used to construct -// queries that explicitly match no documents for the specified value in the given field. -// -// Example usage: -// -// mn := MatchNone("title", "es-query-builder") -// // mn now contains a matchNoneType object that matches no documents for the "title" field with the query "es-query-builder". -// -// Parameters: -// - key: A string representing the field name for the match_none query. -// - query: The value to be used in the match_none query. The type is generic. -// -// Returns: -// -// A matchNoneType object containing the specified match_none query. -func MatchNone[T any](key string, query T) matchNoneType { - return matchNoneType{ - "match_none": Object{ - key: Object{ - "query": query, - }, - }, - } -} - -func (m matchNoneType) putInTheField(key string, value any) matchNoneType { - if matchNone, ok := m["match_none"].(Object); ok { - for _, fieldObj := range matchNone { - if fieldObject, foOk := fieldObj.(Object); foOk { - fieldObject[key] = value - break - } - } - } - return m -} - -// Operator sets the "operator" field in the match_none query. -// -// This method configures the match_none query to use a specified operator (e.g., "AND" or "OR") -// for the matching process. It calls putInTheField to add or update the "operator" key -// in the match_none query object. -// -// Example usage: -// -// mn := MatchNone("title", "es-query-builder").Operator("AND") -// // mn now has an "operator" field set to "AND" in the match_none query object. -// -// Parameters: -// - operator: An Operator.Operator value representing the logical operator to be used in the match_none query. -// -// Returns: -// -// The updated matchNoneType object with the "operator" field set to the specified value. -func (m matchNoneType) Operator(operator Operator.Operator) matchNoneType { - return m.putInTheField("operator", operator) -} - -// Boost sets the "boost" field in the match_none query. -// -// This method configures the match_none query to use a specified boost factor, which influences -// the relevance scoring of the matched documents. It calls putInTheField to add or update -// the "boost" key in the match_none query object. -// -// Example usage: -// -// mn := MatchNone("title", "es-query-builder").Boost(1.5) -// // mn now has a "boost" field set to 1.5 in the match_none query object. -// -// Parameters: -// - boost: A float64 value representing the boost factor to be applied to the match_none query. -// -// Returns: -// -// The updated matchNoneType object with the "boost" field set to the specified value. -func (m matchNoneType) Boost(boost float64) matchNoneType { - return m.putInTheField("boost", boost) -} diff --git a/es/match_none_query_test.go b/es/match_none_query_test.go deleted file mode 100644 index 610133d..0000000 --- a/es/match_none_query_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package es_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/test/assert" - - Operator "github.com/Trendyol/es-query-builder/es/enums/match/operator" -) - -//// MatchNone //// - -func Test_MatchNone_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.MatchNone[any]) -} - -func Test_MatchNone_method_should_create_matchNoneType(t *testing.T) { - // Given - b := es.MatchNone("key", "value") - - // Then - assert.NotNil(t, b) - assert.IsTypeString(t, "es.matchNoneType", b) -} - -func Test_MatchNone_should_create_json_with_match_none_field_inside_query(t *testing.T) { - // Given - query := es.NewQuery( - es.MatchNone("fooBar", "lorem ipsum"). - Boost(6.19). - Operator(Operator.And), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - // nolint:golint,lll - assert.Equal(t, "{\"query\":{\"match_none\":{\"fooBar\":{\"boost\":6.19,\"operator\":\"and\",\"query\":\"lorem ipsum\"}}}}", bodyJSON) -} diff --git a/es/match_query.go b/es/match_query.go deleted file mode 100644 index cbf3c68..0000000 --- a/es/match_query.go +++ /dev/null @@ -1,281 +0,0 @@ -package es - -import ( - Operator "github.com/Trendyol/es-query-builder/es/enums/match/operator" - ZeroTermsQuery "github.com/Trendyol/es-query-builder/es/enums/match/zero-terms-query" -) - -type matchType Object - -// Match creates a new matchType object with the specified field and query. -// -// This function initializes a matchType object for a match query, where the key -// is the field name and query is the value to search for in that field. This is used -// to construct queries that match the specified value in the given field. -// -// Example usage: -// -// m := es.Match("title", "es-query-builder") -// // m now contains a matchType object that matches the query "es-query-builder" in the "title" field. -// -// Parameters: -// - key: A string representing the field name for the match query. -// - query: The value to be matched in the specified field. The type is generic. -// -// Returns: -// -// A matchType object containing the specified match query. -func Match[T any](key string, query T) matchType { - return matchType{ - "match": Object{ - key: Object{ - "query": query, - }, - }, - } -} - -func (m matchType) putInTheField(key string, value any) matchType { - if match, ok := m["match"].(Object); ok { - for _, fieldObj := range match { - if fieldObject, foOk := fieldObj.(Object); foOk { - fieldObject[key] = value - break - } - } - } - return m -} - -// Operator sets the "operator" field in the match query. -// -// This method configures the match query to use a specified operator (e.g., "AND" or "OR") -// for the matching process. -// -// Example usage: -// -// m := es.Match("title", "es-query-builder").Operator("AND") -// // m now has an "operator" field set to "AND" in the match query object. -// -// Parameters: -// - operator: An Operator.Operator value representing the logical operator to be used in the match query. -// -// Returns: -// -// The updated matchType object with the "operator" field set to the specified value. -func (m matchType) Operator(operator Operator.Operator) matchType { - return m.putInTheField("operator", operator) -} - -// Boost sets the "boost" field in the match query. -// -// This method configures the match query to use a specified boost factor, which influences -// the relevance scoring of the matched documents. -// -// Example usage: -// -// m := es.Match("title", "es-query-builder").Boost(1.5) -// // m now has a "boost" field set to 1.5 in the match query object. -// -// Parameters: -// - boost: A float64 value representing the boost factor to be applied to the match query. -// -// Returns: -// -// The updated matchType object with the "boost" field set to the specified value. -func (m matchType) Boost(boost float64) matchType { - return m.putInTheField("boost", boost) -} - -// CutoffFrequency sets the "cutoff_frequency" field in the match query. -// -// This method configures the match query to use a specified cutoff frequency, which is useful -// for controlling how often terms should appear in the document for it to be considered a match. -// A lower cutoff frequency increases precision, while a higher one allows more terms to be matched. -// -// Example usage: -// -// m := es.Match("title", "es-query-builder").CutoffFrequency(0.001) -// // m now has a "cutoff_frequency" field set to 0.001 in the match query object. -// -// Parameters: -// - cutoffFrequency: A float64 value representing the cutoff frequency threshold to be used in the match query. -// -// Returns: -// -// The updated matchType object with the "cutoff_frequency" field set to the specified value. -func (m matchType) CutoffFrequency(cutoffFrequency float64) matchType { - return m.putInTheField("cutoff_frequency", cutoffFrequency) -} - -// Fuzziness sets the "fuzziness" field in the match query. -// -// This method configures the match query to use a specified fuzziness level, which determines -// the allowed edit distance (e.g., number of character changes) for a term to be considered a match. -// Common values include "AUTO", or integers representing the number of edits (e.g., 1 or 2). -// -// Example usage: -// -// m := es.Match("title", "es-query-builder").Fuzziness("AUTO") -// // m now has a "fuzziness" field set to "AUTO" in the match query object. -// -// Parameters: -// - fuzziness: A value of any type (typically a string or integer) representing the fuzziness level to be applied to the match query. -// -// Returns: -// -// The updated matchType object with the "fuzziness" field set to the specified value. -func (m matchType) Fuzziness(fuzziness any) matchType { - return m.putInTheField("fuzziness", fuzziness) -} - -// FuzzyRewrite sets the "fuzzy_rewrite" field in the match query. -// -// This method configures the match query to use a specified fuzzy rewrite method, -// which controls how multi-term queries are rewritten. Common values include "constant_score", -// "scoring_boolean", and other rewrite options that influence the scoring and performance of -// fuzzy matching. -// -// Example usage: -// -// m := es.Match("title", "es-query-builder").FuzzyRewrite("constant_score") -// // m now has a "fuzzy_rewrite" field set to "constant_score" in the match query object. -// -// Parameters: -// - fuzzyRewrite: A string value representing the rewrite method to be used for fuzzy matching in the match query. -// -// Returns: -// -// The updated matchType object with the "fuzzy_rewrite" field set to the specified value. -func (m matchType) FuzzyRewrite(fuzzyRewrite string) matchType { - return m.putInTheField("fuzzy_rewrite", fuzzyRewrite) -} - -// FuzzyTranspositions sets the "fuzzy_transpositions" field in the match query. -// -// This method configures the match query to allow or disallow transpositions (e.g., swapping two adjacent characters) -// when performing fuzzy matching. Setting this field to true enables transpositions, which can increase the match rate -// for terms with common typos or character swaps. -// -// Example usage: -// -// m := es.Match("title", "es-query-builder").FuzzyTranspositions(true) -// // m now has a "fuzzy_transpositions" field set to true in the match query object. -// -// Parameters: -// - fuzzyTranspositions: A boolean value indicating whether transpositions should be allowed in fuzzy matching. -// -// Returns: -// -// The updated matchType object with the "fuzzy_transpositions" field set to the specified value. -func (m matchType) FuzzyTranspositions(fuzzyTranspositions bool) matchType { - return m.putInTheField("fuzzy_transpositions", fuzzyTranspositions) -} - -// Lenient sets the "lenient" field in the match query. -// -// This method configures the match query to use lenient parsing, allowing it to skip errors -// for data type mismatches. When set to true, documents that contain mismatched data types -// (e.g., text in a numeric field) will not cause errors and will be ignored instead. -// -// Example usage: -// -// m := es.Match("title", "es-query-builder").Lenient(true) -// // m now has a "lenient" field set to true in the match query object. -// -// Parameters: -// - lenient: A boolean value indicating whether lenient parsing should be enabled. -// -// Returns: -// -// The updated matchType object with the "lenient" field set to the specified value. -func (m matchType) Lenient(lenient bool) matchType { - return m.putInTheField("lenient", lenient) -} - -// MaxExpansions sets the "max_expansions" field in the match query. -// -// This method configures the match query to limit the maximum number of terms that can be expanded -// for multi-term queries, such as those involving fuzzy matching. Higher values allow more terms to -// be considered, but may impact performance. -// -// Example usage: -// -// m := es.Match("title", "es-query-builder").MaxExpansions(50) -// // m now has a "max_expansions" field set to 50 in the match query object. -// -// Parameters: -// - maxExpansions: An integer representing the maximum number of term expansions to be allowed in the match query. -// -// Returns: -// -// The updated matchType object with the "max_expansions" field set to the specified value. -func (m matchType) MaxExpansions(maxExpansions int) matchType { - return m.putInTheField("max_expansions", maxExpansions) -} - -// PrefixLength sets the "prefix_length" field in the match query. -// -// This method configures the match query to specify a minimum prefix length for fuzzy matching, -// which defines the number of initial characters in a term that must match exactly before -// considering fuzziness. Increasing this value can improve performance by reducing the number -// of fuzzy matches, but may also limit the flexibility of the query. -// -// Example usage: -// -// m := es.Match("title", "es-query-builder").PrefixLength(2) -// // m now has a "prefix_length" field set to 2 in the match query object. -// -// Parameters: -// - prefixLength: An integer representing the number of initial characters that must match exactly in fuzzy matching. -// -// Returns: -// -// The updated matchType object with the "prefix_length" field set to the specified value. -func (m matchType) PrefixLength(prefixLength int) matchType { - return m.putInTheField("prefix_length", prefixLength) -} - -// AutoGenerateSynonymsPhraseQuery sets the "auto_generate_synonyms_phrase_query" field in the match query. -// -// This method enables or disables automatic generation of phrase queries for synonyms in the match query. -// When enabled, the query engine automatically expands the search to include synonym phrases, which can -// enhance results by including terms related to the search term. However, enabling this may increase -// the complexity of the query and affect performance, especially with a large synonym dictionary. -// -// Example usage: -// -// m := es.Match("title", "es-query-builder").AutoGenerateSynonymsPhraseQuery(true) -// // m now has the "auto_generate_synonyms_phrase_query" field set to true in the match query object. -// -// Parameters: -// - autoGenerateSynonymsPhraseQuery: A boolean indicating whether to automatically generate phrase queries for synonyms. -// -// Returns: -// -// The updated matchType object with the "auto_generate_synonyms_phrase_query" field set to the specified value. -func (m matchType) AutoGenerateSynonymsPhraseQuery(autoGenerateSynonymsPhraseQuery bool) matchType { - return m.putInTheField("auto_generate_synonyms_phrase_query", autoGenerateSynonymsPhraseQuery) -} - -// ZeroTermsQuery sets the "zero_terms_query" field in the match query. -// -// This method configures the behavior of the match query when no terms remain after analysis -// (for example, if all terms are stop words). The specified zero_terms_query value determines -// how to handle this scenario, with options like "all" to match all documents or "none" to -// match none. -// -// Example usage: -// -// m := es.Match("title", "es-query-builder").ZeroTermsQuery(zerotermsquery.All) -// // m now has a "zero_terms_query" field set to "all" in the match query object. -// -// Parameters: -// - zeroTermsQuery: A zerotermsquery.ZeroTermsQuery value that specifies the behavior for zero-term queries. -// -// Returns: -// -// The updated matchType object with the "zero_terms_query" field set to the specified value. -func (m matchType) ZeroTermsQuery(zeroTermsQuery ZeroTermsQuery.ZeroTermsQuery) matchType { - return m.putInTheField("zero_terms_query", zeroTermsQuery) -} diff --git a/es/match_query_test.go b/es/match_query_test.go deleted file mode 100644 index 370bfda..0000000 --- a/es/match_query_test.go +++ /dev/null @@ -1,282 +0,0 @@ -package es_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/test/assert" - - Operator "github.com/Trendyol/es-query-builder/es/enums/match/operator" - ZeroTermsQuery "github.com/Trendyol/es-query-builder/es/enums/match/zero-terms-query" -) - -//// Match //// - -func Test_Match_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.Match[any]) -} - -func Test_Match_method_should_create_matchType(t *testing.T) { - // Given - b := es.Match("key", "value") - - // Then - assert.NotNil(t, b) - assert.IsTypeString(t, "es.matchType", b) -} - -func Test_Match_should_have_Boost_method(t *testing.T) { - // Given - term := es.Match("key", "value") - - // When Then - assert.NotNil(t, term.Boost) -} - -func Test_Match_Boost_should_create_json_with_boost_field_inside_match(t *testing.T) { - // Given - query := es.NewQuery( - es.Match("type", "Folder"). - Boost(3.14), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"match\":{\"type\":{\"boost\":3.14,\"query\":\"Folder\"}}}}", bodyJSON) -} - -func Test_Match_should_have_Operator_method(t *testing.T) { - // Given - term := es.Match("key", "value") - - // When Then - assert.NotNil(t, term.Operator) -} - -func Test_Match_Operator_should_create_json_with_operator_field_inside_match(t *testing.T) { - // Given - query := es.NewQuery( - es.Match("type", "Folder"). - Operator(Operator.And), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"match\":{\"type\":{\"operator\":\"and\",\"query\":\"Folder\"}}}}", bodyJSON) -} - -func Test_Match_should_have_CutoffFrequency_method(t *testing.T) { - // Given - term := es.Match("key", "value") - - // When Then - assert.NotNil(t, term.CutoffFrequency) -} - -func Test_Match_CutoffFrequency_should_create_json_with_cutoff_frequency_field_inside_match(t *testing.T) { - // Given - query := es.NewQuery( - es.Match("type", "Folder"). - CutoffFrequency(0.0001), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"match\":{\"type\":{\"cutoff_frequency\":0.0001,\"query\":\"Folder\"}}}}", bodyJSON) -} - -func Test_Match_should_have_Fuzziness_method(t *testing.T) { - // Given - term := es.Match("key", "value") - - // When Then - assert.NotNil(t, term.Fuzziness) -} - -func Test_Match_Fuzziness_should_create_json_with_fuzziness_field_inside_match(t *testing.T) { - // Given - query := es.NewQuery( - es.Match("type", "Folder"). - Fuzziness("AUTO"), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"match\":{\"type\":{\"fuzziness\":\"AUTO\",\"query\":\"Folder\"}}}}", bodyJSON) -} - -func Test_Match_should_have_FuzzyRewrite_method(t *testing.T) { - // Given - term := es.Match("key", "value") - - // When Then - assert.NotNil(t, term.FuzzyRewrite) -} - -func Test_Match_FuzzyRewrite_should_create_json_with_fuzzy_rewrite_field_inside_match(t *testing.T) { - // Given - query := es.NewQuery( - es.Match("type", "Folder"). - FuzzyRewrite("constant_score"), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"match\":{\"type\":{\"fuzzy_rewrite\":\"constant_score\",\"query\":\"Folder\"}}}}", bodyJSON) -} - -func Test_Match_should_have_FuzzyTranspositions_method(t *testing.T) { - // Given - term := es.Match("key", "value") - - // When Then - assert.NotNil(t, term.FuzzyTranspositions) -} - -func Test_Match_FuzzyTranspositions_should_create_json_with_fuzzy_transpositions_field_inside_match(t *testing.T) { - // Given - query := es.NewQuery( - es.Match("type", "Directory"). - FuzzyTranspositions(false), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"match\":{\"type\":{\"fuzzy_transpositions\":false,\"query\":\"Directory\"}}}}", bodyJSON) -} - -func Test_Match_should_have_Lenient_method(t *testing.T) { - // Given - term := es.Match("key", "value") - - // When Then - assert.NotNil(t, term.Lenient) -} - -func Test_Match_Lenient_should_create_json_with_lenient_field_inside_match(t *testing.T) { - // Given - query := es.NewQuery( - es.Match("type", "Folder"). - Lenient(true), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"match\":{\"type\":{\"lenient\":true,\"query\":\"Folder\"}}}}", bodyJSON) -} - -func Test_Match_should_have_MaxExpansions_method(t *testing.T) { - // Given - term := es.Match("key", "value") - - // When Then - assert.NotNil(t, term.MaxExpansions) -} - -func Test_Match_MaxExpansions_should_create_json_with_max_expansions_field_inside_match(t *testing.T) { - // Given - query := es.NewQuery( - es.Match("type", "Folder"). - MaxExpansions(99), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"match\":{\"type\":{\"max_expansions\":99,\"query\":\"Folder\"}}}}", bodyJSON) -} - -func Test_Match_should_have_PrefixLength_method(t *testing.T) { - // Given - term := es.Match("key", "value") - - // When Then - assert.NotNil(t, term.PrefixLength) -} - -func Test_Match_PrefixLength_should_create_json_with_prefix_length_field_inside_match(t *testing.T) { - // Given - query := es.NewQuery( - es.Match("type", "Folder"). - PrefixLength(40), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"match\":{\"type\":{\"prefix_length\":40,\"query\":\"Folder\"}}}}", bodyJSON) -} - -func Test_Match_should_have_AutoGenerateSynonymsPhraseQuery_method(t *testing.T) { - // Given - term := es.Match("key", "value") - - // When Then - assert.NotNil(t, term.AutoGenerateSynonymsPhraseQuery) -} - -func Test_Match_AutoGenerateSynonymsPhraseQuery_should_create_json_auto_generate_synonyms_phrase_query_field_inside_match(t *testing.T) { - // Given - query := es.NewQuery( - es.Match("type", "Folder"). - AutoGenerateSynonymsPhraseQuery(false), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"match\":{\"type\":{\"auto_generate_synonyms_phrase_query\":false,\"query\":\"Folder\"}}}}", bodyJSON) -} - -func Test_Match_should_have_ZeroTermsQuery_method(t *testing.T) { - // Given - term := es.Match("key", "value") - - // When Then - assert.NotNil(t, term.ZeroTermsQuery) -} - -func Test_Match_ZeroTermsQuery_should_create_json_with_zero_terms_query_field_inside_match(t *testing.T) { - // Given - query := es.NewQuery( - es.Match("type", "Folder"). - ZeroTermsQuery(ZeroTermsQuery.All), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"match\":{\"type\":{\"query\":\"Folder\",\"zero_terms_query\":\"all\"}}}}", bodyJSON) -} - -func Test_Match_should_create_json_with_match_field_inside_query(t *testing.T) { - // Given - query := es.NewQuery( - es.Match("message", "this is a test"). - Boost(2.14). - Operator(Operator.Or). - CutoffFrequency(0.241). - Fuzziness("AUTO"). - FuzzyRewrite("constant_score"). - FuzzyTranspositions(true). - Lenient(true). - MaxExpansions(50). - PrefixLength(2). - AutoGenerateSynonymsPhraseQuery(true). - ZeroTermsQuery(ZeroTermsQuery.None), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - // nolint:golint,lll - assert.Equal(t, "{\"query\":{\"match\":{\"message\":{\"auto_generate_synonyms_phrase_query\":true,\"boost\":2.14,\"cutoff_frequency\":0.241,\"fuzziness\":\"AUTO\",\"fuzzy_rewrite\":\"constant_score\",\"fuzzy_transpositions\":true,\"lenient\":true,\"max_expansions\":50,\"operator\":\"or\",\"prefix_length\":2,\"query\":\"this is a test\",\"zero_terms_query\":\"none\"}}}}", bodyJSON) -} diff --git a/es/nested_query.go b/es/nested_query.go deleted file mode 100644 index 89d3079..0000000 --- a/es/nested_query.go +++ /dev/null @@ -1,82 +0,0 @@ -package es - -import ScoreMode "github.com/Trendyol/es-query-builder/es/enums/nested/score-mode" - -type nestedType Object - -// Nested creates a new nestedType object for a nested query. -// -// This function initializes a nested query object with the specified path and query. -// The path represents the field path for the nested query, and the nested query is -// constructed using the es.NewQuery function. -// -// Example usage: -// -// nestedQuery := Nested("comments", es.Bool().Filter(...).MustNot(...)) -// // nestedQuery now contains a nestedType object with the specified path and query. -// -// Parameters: -// - path: A string representing the path for the nested query. -// - nestedQuery: The query to be applied within the nested query. -// -// Returns: -// -// A nestedType object with the "nested" query and specified path. -func Nested[T any](path string, nestedQuery T) nestedType { - o := NewQuery(nestedQuery) - o["path"] = path - return nestedType{ - "nested": o, - } -} - -func (n nestedType) putInNested(key string, value any) nestedType { - if nestedObject, ok := n["nested"].(Object); ok { - nestedObject[key] = value - } - return n -} - -// InnerHits sets the "inner_hits" field for the nested query. -// -// This method specifies the inner hits for the nested query, allowing you to control -// the returned inner documents for the nested query. It uses the putInNested method -// to add or update the "inner_hits" key in the nested query object. -// -// Example usage: -// -// nested := Nested("comments", es.Term("text", "example")) -// nested = nested.InnerHits(Object{"inner": "hits"}) -// // nested now has an "inner_hits" field with the specified Object in the nested query. -// -// Parameters: -// - innerHits: An es.Object representing the inner hits configuration for the nested query. -// -// Returns: -// -// The updated nestedType object with the "inner_hits" field set to the specified value. -func (n nestedType) InnerHits(innerHits Object) nestedType { - return n.putInNested("inner_hits", innerHits) -} - -// ScoreMode sets the "score_mode" field for the nested query. -// -// This method configures how the scores for the nested documents should be calculated -// and combined. It uses the putInNested method to add or update the "score_mode" -// key in the nested query object. -// -// Example usage: -// -// nested := Nested("comments", es.Term("text", "example")) -// nested = nested.ScoreMode(ScoreMode.Sum) -// // nested now has a "score_mode" field with the specified ScoreMode value in the nested query. -// -// Parameters: -// - scoreMode: A ScoreMode.ScoreMode value representing the scoring mode for the nested query. -// -// Returns: -// -// The updated nestedType object with the "score_mode" field set to the specified value. -func (n nestedType) ScoreMode(scoreMode ScoreMode.ScoreMode) nestedType { - return n.putInNested("score_mode", scoreMode) -} diff --git a/es/nested_query_test.go b/es/nested_query_test.go deleted file mode 100644 index bc62216..0000000 --- a/es/nested_query_test.go +++ /dev/null @@ -1,80 +0,0 @@ -package es_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/test/assert" - - ScoreMode "github.com/Trendyol/es-query-builder/es/enums/nested/score-mode" -) - -//// Nested //// - -func Test_Nested_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.Nested[any]) -} - -func Test_Nested_method_should_create_nestedType(t *testing.T) { - // Given - n := es.Nested("path", es.Object{}) - - // Then - assert.NotNil(t, n) - assert.IsTypeString(t, "es.nestedType", n) -} - -func Test_Nested_should_create_query_json_with_nested_field_inside(t *testing.T) { - // Given - query := es.NewQuery( - es.Nested("nested.path", - es.Object{}, - ), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"nested\":{\"path\":\"nested.path\",\"query\":{}}}}", bodyJSON) -} - -func Test_Nested_should_have_InnerHits_method(t *testing.T) { - // Given - n := es.Nested("path", es.Object{}) - - // When Then - assert.NotNil(t, n.InnerHits) -} - -func Test_InnerHits_should_add_inner_hits_field_into_Nested(t *testing.T) { - // Given - query := es.NewQuery( - es.Nested("nested.path", es.Object{}).InnerHits(es.Object{"inner": "hits"}), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"nested\":{\"inner_hits\":{\"inner\":\"hits\"},\"path\":\"nested.path\",\"query\":{}}}}", bodyJSON) -} - -func Test_Nested_should_have_ScoreMode_method(t *testing.T) { - // Given - n := es.Nested("path", es.Object{}) - - // When Then - assert.NotNil(t, n.ScoreMode) -} - -func Test_ScoreMod_should_add_score_mode_field_into_Nested(t *testing.T) { - // Given - query := es.NewQuery( - es.Nested("nested.path", es.Object{}).ScoreMode(ScoreMode.Sum), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"nested\":{\"path\":\"nested.path\",\"query\":{},\"score_mode\":\"sum\"}}}", bodyJSON) -} diff --git a/es/query_string.go b/es/query_string.go deleted file mode 100644 index 3ca869a..0000000 --- a/es/query_string.go +++ /dev/null @@ -1,567 +0,0 @@ -package es - -type queryStringType Object - -// QueryString creates a new queryStringType object with the specified query string. -// -// This function initializes a queryStringType object with a query string, which -// is typically used to perform full-text search queries in Elasticsearch. The query string -// can contain multiple terms and operators, allowing for complex search expressions. -// -// Example usage: -// -// q := QueryString("Foo AND Bar") -// // q now contains a queryStringType object with a query string query. -// -// Parameters: -// - query: The query string to be used in the search. The type is generic and can be -// any type that represents a query string. -// -// Returns: -// -// A queryStringType object containing the specified query string. -func QueryString[T any](query T) queryStringType { - return queryStringType{ - "query_string": Object{ - "query": query, - }, - } -} - -// DefaultField sets the default field for the queryStringType object. -// -// This method specifies the default field to search within if no field is explicitly mentioned -// in the query string. It is useful when you want to perform a query across a single field -// by default when no field is specified in the query string. -// -// Example usage: -// -// b := es.QueryString("value"). -// DefaultField("defaultField") -// -// q := QueryString("Foo Bar").DefaultField("title") -// // q now contains a queryStringType object where the default field for the query is "title". -// -// Parameters: -// - value: A string representing the field name to be used as the default field in the query. -// -// Returns: -// -// The updated queryStringType object with the new "default_field". -func (q queryStringType) DefaultField(value string) queryStringType { - q.putInTheField("default_field", value) - return q -} - -// AllowLeadingWildcard sets the option to allow leading wildcards in the queryStringType object. -// -// This method enables or disables the use of leading wildcards in the query string. -// When set to true, wildcard queries can begin with a wildcard character (* or ?), -// which can be useful for matching terms that share a common suffix. -// -// Example usage: -// -// b := es.QueryString("value"). -// AllowLeadingWildcard(true) -// -// q := QueryString("Fo* bar").AllowLeadingWildcard(true) -// // q now allows leading wildcards in the query string. -// -// Parameters: -// - value: A boolean indicating whether leading wildcards are allowed (true) or not (false). -// -// Returns: -// -// The updated queryStringType object with the "allow_leading_wildcard" option set. -func (q queryStringType) AllowLeadingWildcard(value bool) queryStringType { - q.putInTheField("allow_leading_wildcard", value) - return q -} - -// AnalyzeWildcard sets the option to analyze wildcard terms in the queryStringType object. -// -// This method determines whether wildcard terms in the query string should be analyzed. -// When set to true, wildcard terms (* and ?) will be analyzed by the analyzer defined -// for the field, allowing for more accurate searches when using wildcards. -// -// Example usage: -// -// b := es.QueryString("value"). -// AnalyzeWildcard(true) -// -// q := QueryString("Fo* bar").AnalyzeWildcard(true) -// // q now analyzes wildcard terms in the query string. -// -// Parameters: -// - value: A boolean indicating whether wildcard terms should be analyzed (true) or not (false). -// -// Returns: -// -// The updated queryStringType object with the "analyze_wildcard" option set. -func (q queryStringType) AnalyzeWildcard(value bool) queryStringType { - q.putInTheField("analyze_wildcard", value) - return q -} - -// Analyzer sets the analyzer to be used for the queryStringType object. -// -// This method specifies the analyzer that should be applied to the query string. -// Analyzers are used to process the text, such as tokenizing and normalizing it, -// allowing for more refined and accurate search queries based on the specified analyzer. -// -// Example usage: -// -// b := es.QueryString("value"). -// Analyzer("custom_analyzer") -// -// q := QueryString("Foo Bar").Analyzer("standard") -// // q now uses the "standard" analyzer for processing the query string. -// -// Parameters: -// - value: A string representing the name of the analyzer to be used. -// -// Returns: -// -// The updated queryStringType object with the "analyzer" set. -func (q queryStringType) Analyzer(value string) queryStringType { - q.putInTheField("analyzer", value) - return q -} - -// AutoGenerateSynonymsPhraseQuery sets the option to automatically generate phrase queries for synonyms in the queryStringType object. -// -// This method enables or disables the automatic generation of phrase queries for synonyms in the query string. -// When set to true, Elasticsearch will automatically create phrase queries for terms that have synonyms, -// which can improve search accuracy when working with synonym filters. -// -// Example usage: -// -// b := es.QueryString("value"). -// AutoGenerateSynonymsPhraseQuery(true) -// -// q := QueryString("quick brown fox").AutoGenerateSynonymsPhraseQuery(true) -// // q now automatically generates phrase queries for synonyms in the query string. -// -// Parameters: -// - value: A boolean indicating whether to automatically generate phrase queries for synonyms (true) or not (false). -// -// Returns: -// -// The updated queryStringType object with the "auto_generate_synonyms_phrase_query" option set. -func (q queryStringType) AutoGenerateSynonymsPhraseQuery(value bool) queryStringType { - q.putInTheField("auto_generate_synonyms_phrase_query", value) - return q -} - -// Boost sets the boost factor for the queryStringType object. -// -// This method specifies the boost value to increase or decrease the relevance of the query. -// A higher boost value increases the relevance score of the query, making it more likely -// to appear higher in the search results, while a lower value decreases its importance. -// -// Example usage: -// -// b := es.QueryString("value"). -// Boost(2.0) -// -// q := QueryString("Foo Bar").Boost(1.5) -// // q now has a boost factor of 1.5, increasing its relevance in the search results. -// -// Parameters: -// - value: A float64 representing the boost factor to be applied to the query. -// -// Returns: -// -// The updated queryStringType object with the "boost" value set. -func (q queryStringType) Boost(value float64) queryStringType { - q.putInTheField("boost", value) - return q -} - -// DefaultOperator sets the default operator for the queryStringType object. -// -// This method specifies the default operator to be used between terms in the query string -// when no explicit operator is provided. The default operator can be "AND" or "OR", -// determining whether all terms (AND) or any term (OR) must be matched in the search results. -// -// Example usage: -// -// b := es.QueryString("value"). -// DefaultOperator("AND") -// -// q := QueryString("Foo Bar").DefaultOperator("OR") -// // q now uses "OR" as the default operator, meaning any term can match in the query. -// -// Parameters: -// - value: A string representing the default operator to be used ("AND" or "OR"). -// -// Returns: -// -// The updated queryStringType object with the "default_operator" set. -func (q queryStringType) DefaultOperator(value string) queryStringType { - q.putInTheField("default_operator", value) - return q -} - -// EnablePositionIncrements sets the option to enable or disable position increments in the queryStringType object. -// -// This method determines whether to account for position increments when analyzing the query string. -// When set to true, position increments are taken into account, which can improve the accuracy of -// phrase and proximity queries by considering gaps caused by stopwords or other factors. -// -// Example usage: -// -// b := es.QueryString("value"). -// EnablePositionIncrements(true) -// -// Parameters: -// - value: A boolean indicating whether to enable (true) or disable (false) position increments. -// -// Returns: -// -// The updated queryStringType object with the "enable_position_increments" option set. -func (q queryStringType) EnablePositionIncrements(value bool) queryStringType { - q.putInTheField("enable_position_increments", value) - return q -} - -// Fields sets the fields to be searched within the queryStringType object. -// -// This method specifies a list of fields that the query string should search. -// If multiple fields are provided, the query will search across all of them, -// allowing for more flexible and comprehensive search queries. -// -// Example usage: -// -// b := es.QueryString("value"). -// Fields([]string{"title", "description"}) -// -// q := QueryString("Foo Bar").Fields([]string{"title", "content"}) -// // q now searches within the "title" and "content" fields. -// -// Parameters: -// - value: A slice of strings representing the field names to be searched. -// -// Returns: -// -// The updated queryStringType object with the "fields" option set. -func (q queryStringType) Fields(value []string) queryStringType { - q.putInTheField("fields", value) - return q -} - -// Fuzziness sets the fuzziness level for the queryStringType object. -// -// This method specifies the fuzziness level for the query, allowing for approximate -// matching of terms. Fuzziness is particularly useful for handling misspellings or -// variations in search terms. The fuzziness value can be "AUTO", a number indicating -// the maximum allowed edits, or a specific fuzziness setting. -// -// Example usage: -// -// b := es.QueryString("value"). -// Fuzziness("AUTO") -// -// q := QueryString("Foo Bar").Fuzziness("2") -// // q now uses a fuzziness level of "2" to allow for approximate matching. -// -// Parameters: -// - value: A string representing the fuzziness level (e.g., "AUTO", "1", "2"). -// -// Returns: -// -// The updated queryStringType object with the "fuzziness" option set. -func (q queryStringType) Fuzziness(value string) queryStringType { - q.putInTheField("fuzziness", value) - return q -} - -// FuzzyMaxExpansions sets the maximum number of expansions for fuzzy matching in the queryStringType object. -// -// This method specifies the maximum number of terms that the query will expand to -// when performing fuzzy matching. This setting controls the number of variations -// of the search term that will be considered in the query, affecting both performance -// and accuracy of fuzzy searches. -// -// Example usage: -// -// b := es.QueryString("value"). -// FuzzyMaxExpansions(50) -// -// q := QueryString("Foo Bar").FuzzyMaxExpansions(100) -// // q now allows up to 100 expansions for fuzzy matching. -// -// Parameters: -// - value: An integer representing the maximum number of term expansions for fuzzy matching. -// -// Returns: -// -// The updated queryStringType object with the "fuzzy_max_expansions" option set. -func (q queryStringType) FuzzyMaxExpansions(value int64) queryStringType { - q.putInTheField("fuzzy_max_expansions", value) - return q -} - -// FuzzyPrefixLength sets the prefix length for fuzzy matching in the queryStringType object. -// -// This method specifies the length of the initial characters that must match exactly -// before applying any fuzziness in the query. Increasing the prefix length can improve -// performance by reducing the number of potential matches, while still allowing for -// approximate matching beyond the prefix. -// -// Example usage: -// -// b := es.QueryString("value"). -// FuzzyPrefixLength(2) -// -// q := QueryString("Foo Bar").FuzzyPrefixLength(3) -// // q now requires the first 3 characters to match exactly before applying fuzziness. -// -// Parameters: -// - value: An integer representing the number of initial characters that must match exactly. -// -// Returns: -// -// The updated queryStringType object with the "fuzzy_prefix_length" option set. -func (q queryStringType) FuzzyPrefixLength(value int64) queryStringType { - q.putInTheField("fuzzy_prefix_length", value) - return q -} - -// FuzzyTranspositions sets the option to allow transpositions in fuzzy matching for the queryStringType object. -// -// This method enables or disables the allowance of transpositions (swapping of adjacent characters) -// in fuzzy matching. When set to true, terms that are similar but have transposed characters -// (e.g., "ab" vs. "ba") will still be considered a match, increasing the flexibility of the search. -// -// Example usage: -// -// b := es.QueryString("value"). -// FuzzyTranspositions(true) -// -// q := QueryString("Foo Bar").FuzzyTranspositions(true) -// // q now allows transpositions in fuzzy matching. -// -// Parameters: -// - value: A boolean indicating whether transpositions are allowed (true) or not (false). -// -// Returns: -// -// The updated queryStringType object with the "fuzzy_transpositions" option set. -func (q queryStringType) FuzzyTranspositions(value bool) queryStringType { - q.putInTheField("fuzzy_transpositions", value) - return q -} - -// Lenient sets the leniency option for the queryStringType object. -// -// This method determines whether the query should be lenient when encountering -// errors, such as analyzing incompatible fields. When set to true, the query will -// ignore such errors, allowing for more flexible and fault-tolerant searches, -// especially in cases where the data types may not match perfectly. -// -// Example usage: -// -// b := es.QueryString("value"). -// Lenient(true) -// -// q := QueryString("Foo Bar").Lenient(true) -// // q is now lenient, allowing it to tolerate errors during the query. -// -// Parameters: -// - value: A boolean indicating whether leniency is enabled (true) or disabled (false). -// -// Returns: -// -// The updated queryStringType object with the "lenient" option set. -func (q queryStringType) Lenient(value bool) queryStringType { - q.putInTheField("lenient", value) - return q -} - -// MaxDeterminizedStates sets the maximum number of determinized states for the queryStringType object. -// -// This method specifies the maximum number of states that can be determinized when expanding -// wildcard, prefix, and other complex queries into a finite automaton. Limiting this number -// helps control the potential complexity and resource usage of the query, preventing excessive -// expansion that could impact performance. -// -// Example usage: -// -// b := es.QueryString("value"). -// MaxDeterminizedStates(10000) -// -// q := QueryString("Foo*").MaxDeterminizedStates(5000) -// // q now limits the determinized states to 5000 to control query complexity. -// -// Parameters: -// - value: An integer representing the maximum number of determinized states allowed. -// -// Returns: -// -// The updated queryStringType object with the "max_determinized_states" option set. -func (q queryStringType) MaxDeterminizedStates(value int64) queryStringType { - q.putInTheField("max_determinized_states", value) - return q -} - -// MinimumShouldMatch sets the minimum number of "should" clauses that must match for the queryStringType object. -// -// This method specifies the minimum number of optional ("should") clauses that must match in order -// for a document to be considered a match. This can be expressed as an absolute number or a percentage, -// allowing for fine-tuned control over query matching behavior, especially in complex boolean queries. -// -// Example usage: -// -// b := es.QueryString("value"). -// MinimumShouldMatch("2") -// -// q := QueryString("Foo Bar").MinimumShouldMatch("2") -// // q now requires that at least 2 of the "should" clauses match for a document to be considered a match. -// -// Parameters: -// - value: A string representing the minimum number or percentage of "should" clauses that must match. -// -// Returns: -// -// The updated queryStringType object with the "minimum_should_match" option set. -func (q queryStringType) MinimumShouldMatch(value string) queryStringType { - q.putInTheField("minimum_should_match", value) - return q -} - -// QuoteAnalyzer sets the analyzer to be used for quoted text in the queryStringType object. -// -// This method specifies the analyzer that should be applied to terms within quotes in the query string. -// When a query contains quoted text, this analyzer will be used to process that portion of the query, -// allowing for customized analysis of phrases or exact matches within quotes. -// -// Example usage: -// -// b := es.QueryString("value"). -// QuoteAnalyzer("custom_phrase_analyzer") -// -// q := QueryString("Foo Bar").QuoteAnalyzer("standard") -// // q now uses the "standard" analyzer for quoted text in the query string. -// -// Parameters: -// - value: A string representing the name of the analyzer to be used for quoted text. -// -// Returns: -// -// The updated queryStringType object with the "quote_analyzer" option set. -func (q queryStringType) QuoteAnalyzer(value string) queryStringType { - q.putInTheField("quote_analyzer", value) - return q -} - -// PhraseSlop sets the slop factor for phrase queries in the queryStringType object. -// -// This method specifies the allowed number of positions (or "slop") that terms in a phrase query can be -// moved around while still being considered a match. A higher slop value allows for more flexibility -// in the order and proximity of terms, making it useful for handling variations in phrase structure. -// -// Example usage: -// -// b := es.QueryString("value"). -// PhraseSlop(3) -// -// q := QueryString("Foo Bar").PhraseSlop(2) -// // q now allows a slop of 2 positions for the phrase match, accommodating slight variations in term order. -// -// Parameters: -// - value: An integer representing the maximum number of position increments allowed for the phrase query. -// -// Returns: -// -// The updated queryStringType object with the "phrase_slop" option set. -func (q queryStringType) PhraseSlop(value int64) queryStringType { - q.putInTheField("phrase_slop", value) - return q -} - -// QuoteFieldSuffix sets the field suffix to be used for quoted text in the queryStringType object. -// -// This method specifies a suffix to be appended to the field names when analyzing quoted text in the query string. -// This is useful for applying different analyzers or field mappings to quoted phrases compared to unquoted terms. -// -// Example usage: -// -// b := es.QueryString("value"). -// QuoteFieldSuffix("_quoted") -// -// q := QueryString("Foo Bar").QuoteFieldSuffix("_phrase") -// // q now appends "_phrase" to the field names when processing quoted text in the query string. -// -// Parameters: -// - value: A string representing the suffix to be appended to field names for quoted text. -// -// Returns: -// -// The updated queryStringType object with the "quote_field_suffix" option set. -func (q queryStringType) QuoteFieldSuffix(value string) queryStringType { - q.putInTheField("quote_field_suffix", value) - return q -} - -// Rewrite sets the rewrite method for the queryStringType object. -// -// This method specifies the rewrite method to be used for rewriting the query string. Rewrite methods -// are used to transform the query into a more optimized form for execution, which can affect both -// performance and the accuracy of the search results. Common rewrite methods include "constant_score", -// "scoring_boolean", and others, depending on the specific use case. This parameter is for expert users only. -// Changing the value of this parameter can impact search performance and relevance. -// -// Example usage: -// -// b := es.QueryString("value"). -// Rewrite("constant_score") -// -// q := QueryString("Foo Bar").Rewrite("scoring_boolean") -// // q now uses the "scoring_boolean" rewrite method for optimizing the query execution. -// -// Parameters: -// - value: A string representing the rewrite method to be applied to the query string. -// -// Returns: -// -// The updated queryStringType object with the "rewrite" option set. -func (q queryStringType) Rewrite(value string) queryStringType { - q.putInTheField("rewrite", value) - return q -} - -// TimeZone sets the time zone for date and time fields in the queryStringType object. -// -// This method specifies the time zone to be applied when parsing and interpreting date and time values -// in the query string. Setting the correct time zone ensures accurate date range queries and comparisons, -// especially when dealing with data from multiple time zones. -// -// Example usage: -// -// b := es.QueryString("value"). -// TimeZone("UTC") -// -// q := QueryString("timestamp:[2024-01-01 TO 2024-12-31]").TimeZone("America/New_York") -// // q now applies the "America/New_York" time zone to date and time fields in the query string. -// -// Parameters: -// - value: A string representing the time zone to be used for date and time fields, such as "UTC" or "America/New_York". -// -// Returns: -// -// The updated queryStringType object with the "time_zone" option set. -func (q queryStringType) TimeZone(value string) queryStringType { - q.putInTheField("time_zone", value) - return q -} - -func (q queryStringType) putInTheField(key string, value any) queryStringType { - for _, fieldObj := range q { - if fieldObject, ok := fieldObj.(Object); ok { - fieldObject[key] = value - break - } - } - return q -} diff --git a/es/query_string_test.go b/es/query_string_test.go deleted file mode 100644 index 122136a..0000000 --- a/es/query_string_test.go +++ /dev/null @@ -1,325 +0,0 @@ -package es_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/test/assert" -) - -func Test_QueryString_should_exist_on_es_package(t *testing.T) { - // Given When - assert.NotNil(t, es.QueryString[any]) -} - -func Test_QueryString_method_should_create_queryStringType(t *testing.T) { - // Given When - b := es.QueryString("value") - - // Then - assert.NotNil(t, b) - assert.IsTypeString(t, "es.queryStringType", b) -} - -func Test_QueryString_method_should_create_query_string_with_required_query(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value"), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"query\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_default_field(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value").DefaultField("defaultField"), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"default_field\":\"defaultField\",\"query\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_allow_leading_wildcard(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value").AllowLeadingWildcard(false), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"allow_leading_wildcard\":false,\"query\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_analyze_wildcard(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value").AnalyzeWildcard(true), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"analyze_wildcard\":true,\"query\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_analyzer(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value").Analyzer("value"), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"analyzer\":\"value\",\"query\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_auto_generate_synonyms_phrase_query(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value").AutoGenerateSynonymsPhraseQuery(false), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"auto_generate_synonyms_phrase_query\":false,\"query\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_boost(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value").Boost(2.5), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"boost\":2.5,\"query\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_default_operator(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value").DefaultOperator("value"), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"default_operator\":\"value\",\"query\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_enable_position_increments(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value").EnablePositionIncrements(false), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"enable_position_increments\":false,\"query\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_fields(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value").Fields([]string{"field1", "field2"}), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"fields\":[\"field1\",\"field2\"],\"query\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_fuzziness(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value").Fuzziness("value"), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"fuzziness\":\"value\",\"query\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_fuzzy_max_expansions(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value").FuzzyMaxExpansions(50), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"fuzzy_max_expansions\":50,\"query\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_fuzzy_prefix_length(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value").FuzzyPrefixLength(1), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"fuzzy_prefix_length\":1,\"query\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_fuzzy_transpositions(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value").FuzzyTranspositions(false), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"fuzzy_transpositions\":false,\"query\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_lenient(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value").Lenient(true), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"lenient\":true,\"query\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_max_determinized_states(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value").MaxDeterminizedStates(5000), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"max_determinized_states\":5000,\"query\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_minimum_should_match(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value").MinimumShouldMatch("1"), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"minimum_should_match\":\"1\",\"query\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_quote_analyzer(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value").QuoteAnalyzer("value"), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"query\":\"value\",\"quote_analyzer\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_phrase_slop(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value").PhraseSlop(0), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"phrase_slop\":0,\"query\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_quote_field_suffix(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value").QuoteFieldSuffix("value"), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"query\":\"value\",\"quote_field_suffix\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_rewrite(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value").Rewrite("value"), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"query\":\"value\",\"rewrite\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_time_zone(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value").TimeZone("value"), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"query\":\"value\",\"time_zone\":\"value\"}}}", bodyJSON) -} - -func Test_QueryString_method_should_create_query_string_with_all_parameters(t *testing.T) { - // Given When - b := es.NewQuery( - es.QueryString("value"). - DefaultField("value"). - AllowLeadingWildcard(false). - AnalyzeWildcard(true). - Analyzer("value"). - AutoGenerateSynonymsPhraseQuery(true). - Boost(2.5). - DefaultOperator("value"). - EnablePositionIncrements(true). - Fields([]string{"field1", "field2"}). - Fuzziness("value"). - FuzzyMaxExpansions(2). - FuzzyPrefixLength(1.0). - FuzzyTranspositions(true). - Lenient(true). - MaxDeterminizedStates(2).MinimumShouldMatch("value"). - QuoteAnalyzer("value"). - PhraseSlop(2). - QuoteFieldSuffix("value"). - Rewrite("value"). - TimeZone("value"), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"query_string\":{\"allow_leading_wildcard\":false,\"analyze_wildcard\":true,"+ - "\"analyzer\":\"value\",\"auto_generate_synonyms_phrase_query\":true,"+ - "\"boost\":2.5,\"default_field\":\"value\",\"default_operator\":\"value\","+ - "\"enable_position_increments\":true,\"fields\":[\"field1\",\"field2\"],"+ - "\"fuzziness\":\"value\",\"fuzzy_max_expansions\":2,\"fuzzy_prefix_length\":1,"+ - "\"fuzzy_transpositions\":true,\"lenient\":true,\"max_determinized_states\":2,"+ - "\"minimum_should_match\":\"value\",\"phrase_slop\":2,\"query\":\"value\",\"quote_analyzer\":\"value\","+ - "\"quote_field_suffix\":\"value\",\"rewrite\":\"value\",\"time_zone\":\"value\"}}}", bodyJSON) -} diff --git a/es/range.go b/es/range.go deleted file mode 100644 index 2f509ea..0000000 --- a/es/range.go +++ /dev/null @@ -1,174 +0,0 @@ -package es - -type rangeType Object - -// Range creates a new rangeType object with the specified field. -// -// This function initializes a rangeType object for specifying range queries. The key represents -// the field name, and the rangeType object is used to define the range conditions for that field. -// -// Example usage: -// -// r := Range("age") -// // r now contains a rangeType object with the specified field "age" for range queries. -// -// Parameters: -// - key: A string representing the field name for the range query. -// -// Returns: -// -// A rangeType object with the specified field ready for defining range conditions. -func Range(key string) rangeType { - return rangeType{ - "range": Object{ - key: Object{}, - }, - } -} - -func (r rangeType) putInTheField(key string, value any) rangeType { - if rang, ok := r["range"].(Object); ok { - for field := range rang { - if fieldObject, foOk := rang[field].(Object); foOk { - fieldObject[key] = value - } - } - } - return r -} - -func (r rangeType) delete(key string) rangeType { - if rang, ok := r["range"].(Object); ok { - for field := range rang { - if fieldObject, foOk := rang[field].(Object); foOk { - delete(fieldObject, key) - } - } - } - return r -} - -// LesserThan sets the "lt" (less than) field for the range query. -// -// This method specifies that the range query should match values that are less than -// the provided value. It removes any existing "lte" (less than or equal to) field to ensure -// that only one type of range condition is applied. -// -// Example usage: -// -// r := Range("age").LesserThan(20) -// // r now has an "lt" field set to 20 in the range query for the "age" field. -// -// Parameters: -// - lt: The value that the field should be less than. -// -// Returns: -// -// The updated rangeType object with the "lt" field set to the specified value. -func (r rangeType) LesserThan(lt any) rangeType { - return r.putInTheField("lt", lt).delete("lte") -} - -// LesserThanOrEqual sets the "lte" (less than or equal to) field for the range query. -// -// This method specifies that the range query should match values that are less than or equal -// to the provided value. It removes any existing "lt" (less than) field to ensure that only -// one type of range condition is applied. -// -// Example usage: -// -// r := Range("age").LesserThanOrEqual(20) -// // r now has an "lte" field set to 20 in the range query for the "age" field. -// -// Parameters: -// - lte: The value that the field should be less than or equal to. -// -// Returns: -// -// The updated rangeType object with the "lte" field set to the specified value. -func (r rangeType) LesserThanOrEqual(lte any) rangeType { - return r.putInTheField("lte", lte).delete("lt") -} - -// GreaterThan sets the "gt" (greater than) field for the range query. -// -// This method specifies that the range query should match values that are greater than -// the provided value. It removes any existing "gte" (greater than or equal to) field -// to ensure that only one type of range condition is applied. -// -// Example usage: -// -// r := Range("age").GreaterThan(50) -// // r now has a "gt" field set to 50 in the range query for the "age" field. -// -// Parameters: -// - gt: The value that the field should be greater than. -// -// Returns: -// -// The updated rangeType object with the "gt" field set to the specified value. -func (r rangeType) GreaterThan(gt any) rangeType { - return r.putInTheField("gt", gt).delete("gte") -} - -// GreaterThanOrEqual sets the "gte" (greater than or equal to) field for the range query. -// -// This method specifies that the range query should match values that are greater than or equal -// to the provided value. It removes any existing "gt" (greater than) field to ensure that only -// one type of range condition is applied. -// -// Example usage: -// -// r := Range("age").GreaterThanOrEqual(50) -// // r now has a "gte" field set to 50 in the range query for the "age" field. -// -// Parameters: -// - gte: The value that the field should be greater than or equal to. -// -// Returns: -// -// The updated rangeType object with the "gte" field set to the specified value. -func (r rangeType) GreaterThanOrEqual(gte any) rangeType { - return r.putInTheField("gte", gte).delete("gt") -} - -// Format sets the "format" field for the range query. -// -// This method specifies a format for the range query values, which can be useful for -// controlling how date or numeric values are interpreted. It applies the format to -// all fields in the range query object. -// -// Example usage: -// -// r := Range("date").Format("yyyy-MM-dd") -// // r now has a "format" field set to "yyyy-MM-dd" in the range query for the "date" field. -// -// Parameters: -// - format: A string representing the format to be applied to the range query values. -// -// Returns: -// -// The updated rangeType object with the "format" field set to the specified value. -func (r rangeType) Format(format string) rangeType { - return r.putInTheField("format", format) -} - -// Boost sets the "boost" field for the range query. -// -// This method applies a boost factor to the range query, influencing the relevance scoring -// of documents that match the query. It applies the boost to all fields in the range query object. -// -// Example usage: -// -// r := Range("age").Boost(1.5) -// // r now has a "boost" field set to 1.5 in the range query for the "age" field. -// -// Parameters: -// - boost: A float64 value representing the boost factor to be applied to the range query. -// -// Returns: -// -// The updated rangeType object with the "boost" field set to the specified value. -func (r rangeType) Boost(boost float64) rangeType { - return r.putInTheField("boost", boost) -} diff --git a/es/range_test.go b/es/range_test.go deleted file mode 100644 index 3407947..0000000 --- a/es/range_test.go +++ /dev/null @@ -1,173 +0,0 @@ -package es_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/test/assert" -) - -//// Range //// - -func Test_Range_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.Range) -} - -func Test_Range_should_add_range_field_when_inside_query(t *testing.T) { - // Given - query := es.NewQuery( - es.Bool(). - Must( - es.Range("age"). - GreaterThanOrEqual(10). - LesserThanOrEqual(20), - es.Term("language", "tr"), - ), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - // nolint:golint,lll - assert.Equal(t, "{\"query\":{\"bool\":{\"must\":[{\"range\":{\"age\":{\"gte\":10,\"lte\":20}}},{\"term\":{\"language\":{\"value\":\"tr\"}}}]}}}", bodyJSON) -} - -func Test_Range_method_should_create_rangeType(t *testing.T) { - // Given - b := es.Range("age") - query := es.NewQuery(b) - - // Then - assert.NotNil(t, query) - assert.NotNil(t, b) - assert.IsTypeString(t, "es.rangeType", b) -} - -func Test_Range_should_create_json_with_range_field_inside_query(t *testing.T) { - // Given - query := es.NewQuery( - es.Range("age"). - GreaterThanOrEqual(10). - LesserThanOrEqual(20), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"range\":{\"age\":{\"gte\":10,\"lte\":20}}}}", bodyJSON) -} - -func Test_Range_should_have_LesserThan_method(t *testing.T) { - // Given - r := es.Range("age") - - // When Then - assert.NotNil(t, r) - assert.NotNil(t, r.LesserThan) -} - -func Test_Range_should_have_LesserThanOrEqual_method(t *testing.T) { - // Given - r := es.Range("age") - - // When Then - assert.NotNil(t, r) - assert.NotNil(t, r.LesserThanOrEqual) -} - -func Test_Range_should_have_GreaterThan_method(t *testing.T) { - // Given - r := es.Range("age") - - // When Then - assert.NotNil(t, r) - assert.NotNil(t, r.GreaterThan) -} - -func Test_Range_should_have_GreaterThanOrEqual_method(t *testing.T) { - // Given - r := es.Range("age") - - // When Then - assert.NotNil(t, r) - assert.NotNil(t, r.GreaterThanOrEqual) -} - -func Test_Range_gte_should_override_gt_and_vise_versa(t *testing.T) { - // Given - query := es.NewQuery( - es.Range("age"). - GreaterThanOrEqual(10). - GreaterThan(20), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"range\":{\"age\":{\"gt\":20}}}}", bodyJSON) -} - -func Test_Range_lte_should_override_lt_and_vise_versa(t *testing.T) { - // Given - query := es.NewQuery( - es.Range("age"). - LesserThan(11). - LesserThanOrEqual(23), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"range\":{\"age\":{\"lte\":23}}}}", bodyJSON) -} - -func Test_Range_should_have_Format_method(t *testing.T) { - // Given - r := es.Range("age") - - // When Then - assert.NotNil(t, r) - assert.NotNil(t, r.Format) -} - -func Test_Range_Format_should_create_json_with_range_field_inside_query(t *testing.T) { - // Given - query := es.NewQuery( - es.Range("birth-date"). - GreaterThanOrEqual("1990-01-01"). - LesserThanOrEqual("2024-04-12"). - Format("yyyy-MM-dd"), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - // nolint:golint,lll - assert.Equal(t, "{\"query\":{\"range\":{\"birth-date\":{\"format\":\"yyyy-MM-dd\",\"gte\":\"1990-01-01\",\"lte\":\"2024-04-12\"}}}}", bodyJSON) -} - -func Test_Range_should_have_Boost_method(t *testing.T) { - // Given - r := es.Range("age") - - // When Then - assert.NotNil(t, r) - assert.NotNil(t, r.Boost) -} - -func Test_Range_Boost_should_create_json_with_range_field_inside_query(t *testing.T) { - // Given - query := es.NewQuery( - es.Range("partition"). - GreaterThan(112). - LesserThan(765). - Boost(3.2), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - // nolint:golint,lll - assert.Equal(t, "{\"query\":{\"range\":{\"partition\":{\"boost\":3.2,\"gt\":112,\"lt\":765}}}}", bodyJSON) -} diff --git a/es/regexp_query.go b/es/regexp_query.go deleted file mode 100644 index 92a13d7..0000000 --- a/es/regexp_query.go +++ /dev/null @@ -1,108 +0,0 @@ -package es - -type regexpType Object - -// Regexp creates a new regexpType object with the specified key-value pair. -// -// This function initializes a regexpType object with a single regexp query, where the -// key is the field name and the value is the regexp to search for. This is typically -// used to construct a regexp query in search queries. -// -// Example usage: -// -// t := Regexp("endpoint", "/books/.*") -// // t now contains a regexpType object with a regexp query for the "endpoint" field. -// -// Parameters: -// - key: A string representing the field name for the regexp query. -// - value: The value to be searched for in the specified field. The type is regexp. -// -// Returns: -// -// A regexpType object containing the specified regexp query. -func Regexp(key string, value string) regexpType { - return regexpType{ - "regexp": Object{ - key: Object{ - "value": value, - }, - }, - } -} - -func (r regexpType) putInTheField(key string, value any) regexpType { - if regexp, ok := r["regexp"].(Object); ok { - for _, fieldObj := range regexp { - if fieldObject, foOk := fieldObj.(Object); foOk { - fieldObject[key] = value - break - } - } - } - return r -} - -// Flags Enables optional operators for the regular expression. -// Example usage: -// -// regexp := Regexp("endpoint", "/books/.*").Flags("ALL") -// // regexp now a "flags" field set "ALL" in the regexp query object. -// -// Parameters: -// - flags: A string value representing flags value to be applied to the regexp query. -// -// Returns: -// -// The updated regexp object with the "flags" field set to the specified value. -func (r regexpType) Flags(flags string) regexpType { - return r.putInTheField("flags", flags) -} - -// CaseInsensitive Allows case insensitive matching of the regular expression -// value with the indexed field values when set to true. -// Example usage: -// -// regexp := Regexp("endpoint", "/books/.*").CaseInsensitive(true) -// // regexp now a "case_insensitive" field set true in the regexp query object. -// -// Parameters: -// - caseInsensitive: A bool value representing case insensitive value to be applied to the regexp query. -// -// Returns: -// -// The updated regexp object with the "case_insensitive" field set to the specified value. -func (r regexpType) CaseInsensitive(caseInsensitive bool) regexpType { - return r.putInTheField("case_insensitive", caseInsensitive) -} - -// MaxDeterminizedStates Maximum number of automaton states required for the query. -// Example usage: -// -// regexp := Regexp("endpoint", "/books/.*").MaxDeterminizedStates(10000) -// // regexp now a "max_determinized_states" field set 10000 in the regexp query object. -// -// Parameters: -// - maxDeterminizedStates: A bool value representing max_determinized_states value to be applied to the regexp query. -// -// Returns: -// -// The updated regexp object with the "max_determinized_states" field set to the specified value. -func (r regexpType) MaxDeterminizedStates(maxDeterminizedStates int) regexpType { - return r.putInTheField("max_determinized_states", maxDeterminizedStates) -} - -// ReWrite Method used to rewrite the query. -// Example usage: -// -// regexp := Regexp("endpoint", "/books/.*").ReWrite("a") -// // regexp now a "rewrite" field set "a" in the regexp query object. -// -// Parameters: -// - rewrite: A string value representing rewrite value to be applied to the regexp query. -// -// Returns: -// -// The updated regexp object with the "rewrite" field set to the specified value. -func (r regexpType) ReWrite(rewrite string) regexpType { - return r.putInTheField("rewrite", rewrite) -} diff --git a/es/regexp_query_test.go b/es/regexp_query_test.go deleted file mode 100644 index 6f4fdd5..0000000 --- a/es/regexp_query_test.go +++ /dev/null @@ -1,88 +0,0 @@ -package es_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/test/assert" -) - -//// Regexp //// - -func Test_Regexp_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.Regexp) -} - -func Test_Regexp_should_create_json_with_regexp_field_inside_query(t *testing.T) { - // Given - query := es.NewQuery( - es.Regexp("endpoint", "/books/.*"), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"regexp\":{\"endpoint\":{\"value\":\"/books/.*\"}}}}", bodyJSON) -} - -func Test_Regexp_method_should_create_regexpType(t *testing.T) { - // Given - b := es.Regexp("key", "value") - - // Then - assert.NotNil(t, b) - assert.IsTypeString(t, "es.regexpType", b) -} - -func Test_Regexp_should_create_json_with_match_all_field_inside_caseinsensitive_query(t *testing.T) { - // Given - query := es.NewQuery( - es.Regexp("key", "value1"). - CaseInsensitive(false), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"regexp\":{\"key\":{\"case_insensitive\":false,\"value\":\"value1\"}}}}", bodyJSON) -} - -func Test_Regexp_should_create_json_with_match_all_field_inside_maxdeterminizedstates_query(t *testing.T) { - // Given - query := es.NewQuery( - es.Regexp("key", "value1"). - MaxDeterminizedStates(1000), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"regexp\":{\"key\":{\"max_determinized_states\":1000,\"value\":\"value1\"}}}}", bodyJSON) -} - -func Test_Regexp_should_create_json_with_match_all_field_inside_rewrite_query(t *testing.T) { - // Given - query := es.NewQuery( - es.Regexp("key", "value1"). - ReWrite("a"), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"regexp\":{\"key\":{\"rewrite\":\"a\",\"value\":\"value1\"}}}}", bodyJSON) -} - -func Test_Regexp_should_create_json_with_match_all_field_inside_flags_query(t *testing.T) { - // Given - query := es.NewQuery( - es.Regexp("key", "value1"). - Flags("ALL"), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"regexp\":{\"key\":{\"flags\":\"ALL\",\"value\":\"value1\"}}}}", bodyJSON) -} diff --git a/es/simple_query_string.go b/es/simple_query_string.go deleted file mode 100644 index 02d4685..0000000 --- a/es/simple_query_string.go +++ /dev/null @@ -1,308 +0,0 @@ -package es - -type simpleQueryStringType Object - -// SimpleQueryString creates a new simpleQueryStringType object with the specified query string. -// -// This function initializes a simpleQueryStringType object with a simple query string, which -// is typically used to perform simple text search queries in Elasticsearch. The query string -// can contain multiple terms and operators, allowing for basic search expressions. -// -// Example usage: -// -// q := SimpleQueryString("Foo + Bar") -// // q now contains a simpleQueryStringType object with a simple query string query. -// -// Parameters: -// - query: The query string to be used in the search. The type is generic and can be -// any type that represents a query string. -// -// Returns: -// -// A simpleQueryStringType object containing the specified query string. -func SimpleQueryString[T any](query T) simpleQueryStringType { - return simpleQueryStringType{ - "simple_query_string": Object{ - "query": query, - }, - } -} - -// Fields sets the fields to be searched within the simpleQueryStringType object. -// -// This method specifies a list of fields that the query string should search. -// If multiple fields are provided, the query will search across all of them, -// allowing for more flexible and comprehensive search queries. -// -// Example usage: -// -// q := SimpleQueryString("Foo Bar").Fields([]string{"title", "content"}) -// // q now searches within the "title" and "content" fields. -// -// Parameters: -// - value: A slice of strings representing the field names to be searched. -// -// Returns: -// -// The updated simpleQueryStringType object with the "fields" option set. -func (q simpleQueryStringType) Fields(value []string) simpleQueryStringType { - q.putInTheField("fields", value) - return q -} - -// Analyzer sets the analyzer to be used for the simpleQueryStringType object. -// -// This method specifies the analyzer that should be applied to the query string. -// Analyzers are used to process the text, such as tokenizing and normalizing it, -// allowing for more refined and accurate search queries based on the specified analyzer. -// -// Example usage: -// -// q := SimpleQueryString("Foo Bar").Analyzer("standard") -// // q now uses the "standard" analyzer for processing the query string. -// -// Parameters: -// - value: A string representing the name of the analyzer to be used. -// -// Returns: -// -// The updated simpleQueryStringType object with the "analyzer" set. -func (q simpleQueryStringType) Analyzer(value string) simpleQueryStringType { - q.putInTheField("analyzer", value) - return q -} - -// DefaultOperator sets the default operator for the simpleQueryStringType object. -// -// This method specifies the default operator to be used between terms in the query string -// when no explicit operator is provided. The default operator can be "AND" or "OR", -// determining whether all terms (AND) or any term (OR) must be matched in the search results. -// -// Example usage: -// -// q := es.SimpleQueryString("Foo Bar"). -// DefaultOperator("OR") -// -// q now uses "OR" as the default operator, meaning any term can match in the query. -// -// Parameters: -// - value: A string representing the default operator to be used ("AND" or "OR"). -// -// Returns: -// -// The updated simpleQueryStringType object with the "default_operator" set. -func (q simpleQueryStringType) DefaultOperator(value string) simpleQueryStringType { - q.putInTheField("default_operator", value) - return q -} - -// MinimumShouldMatch sets the minimum number of clauses that must match for the simpleQueryStringType object. -// -// This method specifies the minimum number of clauses that must match in order -// for a document to be considered a match. This can be expressed as an absolute number or a percentage, -// allowing for fine-tuned control over query matching behavior. -// -// Example usage: -// -// q := SimpleQueryString("Foo Bar Baz").MinimumShouldMatch("2") -// // q now requires that at least 2 of the terms match for a document to be considered a match. -// -// Parameters: -// - value: A string representing the minimum number or percentage of clauses that must match. -// -// Returns: -// -// The updated simpleQueryStringType object with the "minimum_should_match" option set. -func (q simpleQueryStringType) MinimumShouldMatch(value string) simpleQueryStringType { - q.putInTheField("minimum_should_match", value) - return q -} - -// FuzzyMaxExpansions sets the maximum number of expansions for fuzzy matching in the simpleQueryStringType object. -// -// This method specifies the maximum number of terms that the query will expand to -// when performing fuzzy matching. This setting controls the number of variations -// of the search term that will be considered in the query, affecting both performance -// and accuracy of fuzzy searches. -// -// Example usage: -// -// q := SimpleQueryString("Foo~").FuzzyMaxExpansions(50) -// // q now allows up to 50 expansions for fuzzy matching. -// -// Parameters: -// - value: An integer representing the maximum number of term expansions for fuzzy matching. -// -// Returns: -// -// The updated simpleQueryStringType object with the "fuzzy_max_expansions" option set. -func (q simpleQueryStringType) FuzzyMaxExpansions(value int64) simpleQueryStringType { - q.putInTheField("fuzzy_max_expansions", value) - return q -} - -// FuzzyPrefixLength sets the prefix length for fuzzy matching in the simpleQueryStringType object. -// -// This method specifies the length of the initial characters that must match exactly -// before applying any fuzziness in the query. Increasing the prefix length can improve -// performance by reducing the number of potential matches, while still allowing for -// approximate matching beyond the prefix. -// -// Example usage: -// -// q := SimpleQueryString("Foo~").FuzzyPrefixLength(2) -// // q now requires the first 2 characters to match exactly before applying fuzziness. -// -// Parameters: -// - value: An integer representing the number of initial characters that must match exactly. -// -// Returns: -// -// The updated simpleQueryStringType object with the "fuzzy_prefix_length" option set. -func (q simpleQueryStringType) FuzzyPrefixLength(value int64) simpleQueryStringType { - q.putInTheField("fuzzy_prefix_length", value) - return q -} - -// FuzzyTranspositions sets the option to allow transpositions in fuzzy matching for the simpleQueryStringType object. -// -// This method enables or disables the allowance of transpositions (swapping of adjacent characters) -// in fuzzy matching. When set to true, terms that are similar but have transposed characters -// (e.g., "ab" vs. "ba") will still be considered a match, increasing the flexibility of the search. -// -// Example usage: -// -// q := SimpleQueryString("Foo~").FuzzyTranspositions(true) -// // q now allows transpositions in fuzzy matching. -// -// Parameters: -// - value: A boolean indicating whether transpositions are allowed (true) or not (false). -// -// Returns: -// -// The updated simpleQueryStringType object with the "fuzzy_transpositions" option set. -func (q simpleQueryStringType) FuzzyTranspositions(value bool) simpleQueryStringType { - q.putInTheField("fuzzy_transpositions", value) - return q -} - -// AnalyzeWildcard sets the option to analyze wildcard terms in the simpleQueryStringType object. -// -// This method determines whether wildcard terms in the query string should be analyzed. -// When set to true, wildcard terms (* and ?) will be analyzed by the analyzer defined -// for the field, allowing for more accurate searches when using wildcards. -// -// Example usage: -// -// q := SimpleQueryString("Fo*").AnalyzeWildcard(true) -// // q now analyzes wildcard terms in the query string. -// -// Parameters: -// - value: A boolean indicating whether wildcard terms should be analyzed (true) or not (false). -// -// Returns: -// -// The updated simpleQueryStringType object with the "analyze_wildcard" option set. -func (q simpleQueryStringType) AnalyzeWildcard(value bool) simpleQueryStringType { - q.putInTheField("analyze_wildcard", value) - return q -} - -// AutoGenerateSynonymsPhraseQuery sets the option to automatically generate phrase queries for synonyms -// in the simpleQueryStringType object. -// -// This method enables or disables the automatic generation of phrase queries for synonyms in the query string. -// When set to true, Elasticsearch will automatically create phrase queries for terms that have synonyms, -// which can improve search accuracy when working with synonym filters. -// -// Example usage: -// -// q := SimpleQueryString("quick brown fox").AutoGenerateSynonymsPhraseQuery(true) -// // q now automatically generates phrase queries for synonyms in the query string. -// -// Parameters: -// - value: A boolean indicating whether to automatically generate phrase queries for synonyms (true) or not (false). -// -// Returns: -// -// The updated simpleQueryStringType object with the "auto_generate_synonyms_phrase_query" option set. -func (q simpleQueryStringType) AutoGenerateSynonymsPhraseQuery(value bool) simpleQueryStringType { - q.putInTheField("auto_generate_synonyms_phrase_query", value) - return q -} - -// Flags sets the flags for the simpleQueryStringType object. -// -// This method specifies which features of the simple_query_string query should be enabled. -// It allows fine-grained control over the query's behavior by enabling or disabling specific features. -// -// Example usage: -// -// q := SimpleQueryString("Foo Bar").Flags("AND|OR|PREFIX") -// // q now enables AND, OR, and PREFIX features for the query. -// -// Parameters: -// - value: A string representing the enabled features, separated by '|'. -// Possible values include: ALL, NONE, AND, OR, NOT, PREFIX, PHRASE, PRECEDENCE, ESCAPE, WHITESPACE, FUZZY, NEAR, SLOP. -// -// Returns: -// -// The updated simpleQueryStringType object with the "flags" option set. -func (q simpleQueryStringType) Flags(value string) simpleQueryStringType { - q.putInTheField("flags", value) - return q -} - -// Lenient sets the leniency option for the simpleQueryStringType object. -// -// This method determines whether the query should be lenient when encountering -// errors, such as analyzing incompatible fields. When set to true, the query will -// ignore such errors, allowing for more flexible and fault-tolerant searches, -// especially in cases where the data types may not match perfectly. -// -// Example usage: -// -// q := SimpleQueryString("Foo Bar").Lenient(true) -// // q is now lenient, allowing it to tolerate errors during the query. -// -// Parameters: -// - value: A boolean indicating whether leniency is enabled (true) or disabled (false). -// -// Returns: -// -// The updated simpleQueryStringType object with the "lenient" option set. -func (q simpleQueryStringType) Lenient(value bool) simpleQueryStringType { - q.putInTheField("lenient", value) - return q -} - -// QuoteFieldSuffix sets the field suffix to be used for quoted text in the simpleQueryStringType object. -// -// This method specifies a suffix to be appended to the field names when analyzing quoted text in the query string. -// This is useful for applying different analyzers or field mappings to quoted phrases compared to unquoted terms. -// -// Example usage: -// -// q := SimpleQueryString("Foo \"Bar Baz\"").QuoteFieldSuffix("_phrase") -// // q now appends "_phrase" to the field names when processing quoted text in the query string. -// -// Parameters: -// - value: A string representing the suffix to be appended to field names for quoted text. -// -// Returns: -// -// The updated simpleQueryStringType object with the "quote_field_suffix" option set. -func (q simpleQueryStringType) QuoteFieldSuffix(value string) simpleQueryStringType { - q.putInTheField("quote_field_suffix", value) - return q -} - -func (q simpleQueryStringType) putInTheField(key string, value any) simpleQueryStringType { - for _, fieldObj := range q { - if fieldObject, ok := fieldObj.(Object); ok { - fieldObject[key] = value - break - } - } - return q -} diff --git a/es/simple_query_string_test.go b/es/simple_query_string_test.go deleted file mode 100644 index 9347daf..0000000 --- a/es/simple_query_string_test.go +++ /dev/null @@ -1,216 +0,0 @@ -package es_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/test/assert" -) - -func Test_SimpleQueryString_should_exist_on_es_package(t *testing.T) { - // Given When - assert.NotNil(t, es.SimpleQueryString[any]) -} - -func Test_SimpleQueryString_method_should_create_simpleQueryStringType(t *testing.T) { - // Given When - b := es.SimpleQueryString("value") - - // Then - assert.NotNil(t, b) - assert.IsTypeString(t, "es.simpleQueryStringType", b) -} - -func Test_SimpleQueryString_method_should_create_simple_query_string_with_required_query(t *testing.T) { - // Given When - b := es.NewQuery( - es.SimpleQueryString("value"), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"simple_query_string\":{\"query\":\"value\"}}}", bodyJSON) -} - -func Test_SimpleQueryString_method_should_create_simple_query_string_with_fields(t *testing.T) { - // Given When - b := es.NewQuery( - es.SimpleQueryString("value").Fields([]string{"field1", "field2"}), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"simple_query_string\":{\"fields\":[\"field1\",\"field2\"],\"query\":\"value\"}}}", bodyJSON) -} - -func Test_SimpleQueryString_method_should_create_simple_query_string_with_analyzer(t *testing.T) { - // Given When - b := es.NewQuery( - es.SimpleQueryString("value").Analyzer("standard"), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"simple_query_string\":{\"analyzer\":\"standard\",\"query\":\"value\"}}}", bodyJSON) -} - -func Test_SimpleQueryString_method_should_create_simple_query_string_with_default_operator(t *testing.T) { - // Given When - b := es.NewQuery( - es.SimpleQueryString("value").DefaultOperator("AND"), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"simple_query_string\":{\"default_operator\":\"AND\",\"query\":\"value\"}}}", bodyJSON) -} - -func Test_SimpleQueryString_method_should_create_simple_query_string_with_minimum_should_match(t *testing.T) { - // Given When - b := es.NewQuery( - es.SimpleQueryString("value").MinimumShouldMatch("2"), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"simple_query_string\":{\"minimum_should_match\":\"2\",\"query\":\"value\"}}}", bodyJSON) -} - -func Test_SimpleQueryString_method_should_create_simple_query_string_with_fuzzy_max_expansions(t *testing.T) { - // Given When - b := es.NewQuery( - es.SimpleQueryString("value").FuzzyMaxExpansions(50), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"simple_query_string\":{\"fuzzy_max_expansions\":50,\"query\":\"value\"}}}", bodyJSON) -} - -func Test_SimpleQueryString_method_should_create_simple_query_string_with_fuzzy_prefix_length(t *testing.T) { - // Given When - b := es.NewQuery( - es.SimpleQueryString("value").FuzzyPrefixLength(2), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"simple_query_string\":{\"fuzzy_prefix_length\":2,\"query\":\"value\"}}}", bodyJSON) -} - -func Test_SimpleQueryString_method_should_create_simple_query_string_with_fuzzy_transpositions(t *testing.T) { - // Given When - b := es.NewQuery( - es.SimpleQueryString("value").FuzzyTranspositions(true), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"simple_query_string\":{\"fuzzy_transpositions\":true,\"query\":\"value\"}}}", bodyJSON) -} - -func Test_SimpleQueryString_method_should_create_simple_query_string_with_analyze_wildcard(t *testing.T) { - // Given When - b := es.NewQuery( - es.SimpleQueryString("value").AnalyzeWildcard(true), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"simple_query_string\":{\"analyze_wildcard\":true,\"query\":\"value\"}}}", bodyJSON) -} - -func Test_SimpleQueryString_method_should_create_simple_query_string_with_auto_generate_synonyms_phrase_query(t *testing.T) { - // Given When - b := es.NewQuery( - es.SimpleQueryString("value").AutoGenerateSynonymsPhraseQuery(true), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"simple_query_string\":{\"auto_generate_synonyms_phrase_query\":true,\"query\":\"value\"}}}", bodyJSON) -} - -func Test_SimpleQueryString_method_should_create_simple_query_string_with_flags(t *testing.T) { - // Given When - b := es.NewQuery( - es.SimpleQueryString("value").Flags("AND|OR|PREFIX"), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"simple_query_string\":{\"flags\":\"AND|OR|PREFIX\",\"query\":\"value\"}}}", bodyJSON) -} - -func Test_SimpleQueryString_method_should_create_simple_query_string_with_lenient(t *testing.T) { - // Given When - b := es.NewQuery( - es.SimpleQueryString("value").Lenient(true), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"simple_query_string\":{\"lenient\":true,\"query\":\"value\"}}}", bodyJSON) -} - -func Test_SimpleQueryString_method_should_create_simple_query_string_with_quote_field_suffix(t *testing.T) { - // Given When - b := es.NewQuery( - es.SimpleQueryString("value").QuoteFieldSuffix("_phrase"), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"simple_query_string\":{\"query\":\"value\",\"quote_field_suffix\":\"_phrase\"}}}", bodyJSON) -} - -func Test_SimpleQueryString_method_should_create_simple_query_string_with_all_parameters(t *testing.T) { - // Given When - b := es.NewQuery( - es.SimpleQueryString("value"). - Fields([]string{"field1", "field2"}). - Analyzer("standard"). - DefaultOperator("AND"). - MinimumShouldMatch("2"). - FuzzyMaxExpansions(50). - FuzzyPrefixLength(2). - FuzzyTranspositions(true). - AnalyzeWildcard(true). - AutoGenerateSynonymsPhraseQuery(true). - Flags("AND|OR|PREFIX"). - Lenient(true). - QuoteFieldSuffix("_phrase"), - ) - - // Then - assert.NotNil(t, b) - bodyJSON := assert.MarshalWithoutError(t, b) - assert.Equal(t, "{\"query\":{\"simple_query_string\":{"+ - "\"analyze_wildcard\":true,"+ - "\"analyzer\":\"standard\","+ - "\"auto_generate_synonyms_phrase_query\":true,"+ - "\"default_operator\":\"AND\","+ - "\"fields\":[\"field1\",\"field2\"],"+ - "\"flags\":\"AND|OR|PREFIX\","+ - "\"fuzzy_max_expansions\":50,"+ - "\"fuzzy_prefix_length\":2,"+ - "\"fuzzy_transpositions\":true,"+ - "\"lenient\":true,"+ - "\"minimum_should_match\":\"2\","+ - "\"query\":\"value\","+ - "\"quote_field_suffix\":\"_phrase\""+ - "}}}", bodyJSON) -} diff --git a/es/term_query.go b/es/term_query.go deleted file mode 100644 index b0ac48b..0000000 --- a/es/term_query.go +++ /dev/null @@ -1,141 +0,0 @@ -package es - -type termType Object - -// Term creates a new termType object with the specified key-value pair. -// -// This function initializes a termType object with a single term query, where the -// key is the field name and the value is the term to search for. This is typically -// used to construct a term query in search queries. -// -// Example usage: -// -// t := Term("category", "books") -// // t now contains a termType object with a term query for the "category" field. -// -// Parameters: -// - key: A string representing the field name for the term query. -// - value: The value to be searched for in the specified field. The type is generic. -// -// Returns: -// -// A termType object containing the specified term query. -func Term[T any](key string, value T) termType { - return termType{ - "term": Object{ - key: Object{ - "value": value, - }, - }, - } -} - -func (t termType) putInTheField(key string, value any) termType { - if term, ok := t["term"].(Object); ok { - for field := range term { - if fieldObject, foOk := term[field].(Object); foOk { - fieldObject[key] = value - } - } - } - return t -} - -// CaseInsensitive sets the "case_insensitive" parameter in a termType query. -// -// This method allows you to specify whether the term query should be case- -// insensitive. When set to true, the term matching will ignore case, -// allowing for more flexible matches in the query results. -// -// Example usage: -// -// t := Term().CaseInsensitive(true) -// // t now includes a "case_insensitive" parameter set to true. -// -// Parameters: -// - caseInsensitive: A boolean value indicating whether the term query -// should be case-insensitive. -// -// Returns: -// -// The updated termType object with the "case_insensitive" parameter set. -func (t termType) CaseInsensitive(caseInsensitive bool) termType { - return t.putInTheField("case_insensitive", caseInsensitive) -} - -// Boost sets the "boost" parameter in a termType query. -// -// This method allows you to specify a boost factor for the term query, -// which influences the relevance score of matching documents. A higher -// boost value increases the importance of the term in the query, -// resulting in higher scores for documents that match this term. -// -// Example usage: -// -// t := Term().Boost(1.5) -// // t now includes a "boost" parameter set to 1.5. -// -// Parameters: -// - boost: A float64 value representing the boost factor for the term -// query. -// -// Returns: -// -// The updated termType object with the "boost" parameter set. -func (t termType) Boost(boost float64) termType { - return t.putInTheField("boost", boost) -} - -// TermFunc creates a termType object based on a condition evaluated by a function. -// -// This function conditionally creates a termType object if the provided function -// returns true for the given key-value pair. If the function returns false, it -// returns nil instead of creating a termType object. -// -// Example usage: -// -// t := TermFunc("category", "books", func(key, value string) bool { -// return value != "" -// }) -// // t is either a termType object or nil based on the condition. -// -// Parameters: -// - key: A string representing the field name for the term query. -// - value: The value to be searched for in the specified field. The type is generic. -// - f: A function that takes a key and value, and returns a boolean indicating -// whether to create the termType object. -// -// Returns: -// -// A termType object if the condition is true; otherwise, nil. -func TermFunc[T any](key string, value T, f func(key string, value T) bool) termType { - if !f(key, value) { - return nil - } - return Term(key, value) -} - -// TermIf creates a termType object based on a boolean condition. -// -// This function creates a termType object if the provided condition is true. If -// the condition is false, it returns nil instead of creating a termType object. -// -// Example usage: -// -// t := TermIf("category", "books", true) -// // t is a termType object if the condition is true; otherwise, it is nil. -// -// Parameters: -// - key: A string representing the field name for the term query. -// - value: The value to be searched for in the specified field. The type is generic. -// - condition: A boolean value that determines whether to create the termType object. -// -// Returns: -// -// A termType object if the condition is true; otherwise, nil. -func TermIf[T any](key string, value T, condition bool) termType { - if !condition { - return nil - } - return Term(key, value) -} diff --git a/es/term_query_test.go b/es/term_query_test.go deleted file mode 100644 index b1eba5b..0000000 --- a/es/term_query_test.go +++ /dev/null @@ -1,206 +0,0 @@ -package es_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/test/assert" -) - -//// Term //// - -func Test_Term_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.Term[any]) -} - -func Test_Term_should_create_json_with_term_field_inside_query(t *testing.T) { - // Given - query := es.NewQuery( - es.Term("key", "value"), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"term\":{\"key\":{\"value\":\"value\"}}}}", bodyJSON) -} - -func Test_Term_method_should_create_termType(t *testing.T) { - // Given - b := es.Term("key", "value") - - // Then - assert.NotNil(t, b) - assert.IsTypeString(t, "es.termType", b) -} - -func Test_Term_should_have_CaseInsensitive_method(t *testing.T) { - // Given - term := es.Term("key", "value") - - // When Then - assert.NotNil(t, term.CaseInsensitive) -} - -func Test_Term_CaseInsensitive_should_create_json_with_case_insensitive_field_inside_term(t *testing.T) { - // Given - query := es.NewQuery( - es.Term("type", "File"). - CaseInsensitive(true), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"term\":{\"type\":{\"case_insensitive\":true,\"value\":\"File\"}}}}", bodyJSON) -} - -func Test_Term_should_have_Boost_method(t *testing.T) { - // Given - term := es.Term("key", "value") - - // When Then - assert.NotNil(t, term.CaseInsensitive) -} - -func Test_Term_Boost_should_create_json_with_boost_field_inside_term(t *testing.T) { - // Given - query := es.NewQuery( - es.Term("type", "File"). - Boost(3.14), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"term\":{\"type\":{\"boost\":3.14,\"value\":\"File\"}}}}", bodyJSON) -} - -//// TermFunc //// - -func Test_TermFunc_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.TermFunc[any]) -} - -func Test_TermFunc_should_create_json_with_term_field_inside_query(t *testing.T) { - // Given - query := es.NewQuery( - es.TermFunc("key", "value", func(key string, value string) bool { - return true - }), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"term\":{\"key\":{\"value\":\"value\"}}}}", bodyJSON) -} - -func Test_TermFunc_should_not_add_term_field_inside_query_when_callback_result_is_false(t *testing.T) { - // Given - query := es.NewQuery( - es.TermFunc("key", "value", func(key string, value string) bool { - return false - }), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{}}", bodyJSON) -} - -func Test_TermFunc_should_add_only_term_fields_inside_the_query_when_callback_result_is_true(t *testing.T) { - // Given - query := es.NewQuery( - es.Bool(). - Filter( - es.TermFunc("a", "b", func(key string, value string) bool { - return true - }), - es.TermFunc("c", "d", func(key string, value string) bool { - return false - }), - es.TermFunc("e", "f", func(key string, value string) bool { - return true - }), - ), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - // nolint:golint,lll - assert.Equal(t, "{\"query\":{\"bool\":{\"filter\":[{\"term\":{\"a\":{\"value\":\"b\"}}},{\"term\":{\"e\":{\"value\":\"f\"}}}]}}}", bodyJSON) -} - -func Test_TermFunc_method_should_create_termType(t *testing.T) { - // Given - b := es.TermFunc("key", "value", func(key string, value string) bool { - return true - }) - - // Then - assert.NotNil(t, b) - assert.IsTypeString(t, "es.termType", b) -} - -//// TermIf //// - -func Test_TermIf_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.TermIf[any]) -} - -func Test_TermIf_should_create_json_with_term_field_inside_query(t *testing.T) { - // Given - query := es.NewQuery( - es.TermIf("key", "value", true), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"term\":{\"key\":{\"value\":\"value\"}}}}", bodyJSON) -} - -func Test_TermIf_should_not_add_term_field_inside_query_when_condition_is_false(t *testing.T) { - // Given - query := es.NewQuery( - es.TermIf("key", "value", false), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{}}", bodyJSON) -} - -func Test_TermIf_should_add_only_term_fields_inside_the_query_when_condition_is_true(t *testing.T) { - // Given - query := es.NewQuery( - es.Bool(). - Filter( - es.TermIf("a", "b", true), - es.TermIf("c", "d", false), - es.TermIf("e", "f", true), - ), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - // nolint:golint,lll - assert.Equal(t, "{\"query\":{\"bool\":{\"filter\":[{\"term\":{\"a\":{\"value\":\"b\"}}},{\"term\":{\"e\":{\"value\":\"f\"}}}]}}}", bodyJSON) -} - -func Test_TermIf_method_should_create_termType(t *testing.T) { - // Given - b := es.TermIf("key", "value", true) - - // Then - assert.NotNil(t, b) - assert.IsTypeString(t, "es.termType", b) -} diff --git a/es/terms_query.go b/es/terms_query.go deleted file mode 100644 index ff3cd82..0000000 --- a/es/terms_query.go +++ /dev/null @@ -1,143 +0,0 @@ -package es - -type termsType Object - -// Terms creates a new termsType object with the specified key and values. -// -// This function initializes a termsType object for a terms query, where the key -// is the field name and values is a variadic list of terms to search for in that field. -// This is used to construct queries that match any of the specified terms. -// -// Example usage: -// -// t := Terms("category", "books", "electronics") -// // t now contains a termsType object with a terms query for the "category" field. -// -// Parameters: -// - key: A string representing the field name for the terms query. -// - values: A variadic list of values to be searched for in the specified field. -// The type is generic. -// -// Returns: -// -// A termsType object containing the specified terms query. -func Terms(key string, values ...any) termsType { - return termsType{ - "terms": Object{ - key: values, - }, - } -} - -func (t termsType) putInTheField(key string, value any) termsType { - if terms, ok := t["terms"].(Object); ok { - terms[key] = value - } - return t -} - -// Boost sets the "boost" parameter in a termsType query. -// -// This method allows you to specify a boost factor for the terms query, -// which influences the relevance score of documents matching any of the -// specified terms. A higher boost value increases the importance of the -// terms in the query, resulting in higher scores for documents that match -// any of these terms. -// -// Example usage: -// -// t := Terms().Boost(1.5) -// // t now includes a "boost" parameter set to 1.5. -// -// Parameters: -// - boost: A float64 value representing the boost factor for the terms -// query. -// -// Returns: -// -// The updated termsType object with the "boost" parameter set. -func (t termsType) Boost(boost float64) termsType { - return t.putInTheField("boost", boost) -} - -// TermsArray creates a new termsType object with the specified key and values as a slice. -// -// This function initializes a termsType object for a terms query, where the key -// is the field name and values is a slice of terms to search for in that field. -// This is useful for cases where the terms are provided as a slice instead of -// a variadic list. -// -// Example usage: -// -// t := TermsArray("category", []string{"books", "electronics"}) -// // t now contains a termsType object with a terms query for the "category" field. -// -// Parameters: -// - key: A string representing the field name for the terms query. -// - values: A slice of values to be searched for in the specified field. -// The type is generic. -// -// Returns: -// -// A termsType object containing the specified terms query. -func TermsArray[T any](key string, values []T) termsType { - return termsType{ - "terms": Object{ - key: values, - }, - } -} - -// TermsFunc creates a termsType object based on a condition evaluated by a function. -// -// This function conditionally creates a termsType object if the provided function -// returns true for the given key and values. If the function returns false, it -// returns nil instead of creating a termsType object. -// -// Example usage: -// -// t := TermsFunc("category", []string{"books", "electronics"}, func(key string, values []string) bool { -// return len(values) > 0 -// }) -// // t is either a termsType object or nil based on the condition. -// -// Parameters: -// - key: A string representing the field name for the terms query. -// - values: A slice of values to be searched for in the specified field. -// - f: A function that takes a key and values, and returns a boolean indicating -// whether to create the termsType object. -// -// Returns: -// -// A termsType object if the condition is true; otherwise, nil. -func TermsFunc[T any](key string, values []T, f func(key string, values []T) bool) termsType { - if !f(key, values) { - return nil - } - return TermsArray(key, values) -} - -// TermsIf creates a termsType object based on a boolean condition. -// -// This function creates a termsType object if the provided condition is true. If -// the condition is false, it returns nil instead of creating a termsType object. -// -// Example usage: -// -// t := TermsIf("category", []string{"books", "electronics"}, true) -// // t is a termsType object if the condition is true; otherwise, it is nil. -// -// Parameters: -// - key: A string representing the field name for the terms query. -// - values: A slice of values to be searched for in the specified field. -// - condition: A boolean value that determines whether to create the termsType object. -// -// Returns: -// -// A termsType object if the condition is true; otherwise, nil. -func TermsIf[T any](key string, values []T, condition bool) termsType { - if !condition { - return nil - } - return TermsArray(key, values) -} diff --git a/es/terms_query_test.go b/es/terms_query_test.go deleted file mode 100644 index e58c199..0000000 --- a/es/terms_query_test.go +++ /dev/null @@ -1,211 +0,0 @@ -package es_test - -import ( - "testing" - - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/test/assert" -) - -//// Terms //// - -func Test_Terms_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.Terms) -} - -func Test_Terms_should_create_json_with_terms_field_inside_query(t *testing.T) { - // Given - query := es.NewQuery( - es.Terms("key", "value1", "value2", "value3"), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"terms\":{\"key\":[\"value1\",\"value2\",\"value3\"]}}}", bodyJSON) -} - -func Test_Terms_method_should_create_termsType(t *testing.T) { - // Given - b := es.Terms("key", "value1", "value2", "value3") - - // Then - assert.NotNil(t, b) - assert.IsTypeString(t, "es.termsType", b) -} - -func Test_Terms_should_have_Boost_method(t *testing.T) { - // Given - terms := es.Terms("key", "value1", "value2", "value3") - - // When Then - assert.NotNil(t, terms.Boost) -} - -func Test_Terms_Boost_should_create_json_with_boost_field_inside_terms(t *testing.T) { - // Given - query := es.NewQuery( - es.Terms("sector.name", "a1", "b2", "c3"). - Boost(2.718), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"terms\":{\"boost\":2.718,\"sector.name\":[\"a1\",\"b2\",\"c3\"]}}}", bodyJSON) -} - -//// TermsArray //// - -func Test_TermsArray_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.TermsArray[string]) -} - -func Test_TermsArray_should_create_json_with_terms_field_inside_query(t *testing.T) { - // Given - query := es.NewQuery( - es.TermsArray("key", []any{"value1", "value2", "value3"}), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"terms\":{\"key\":[\"value1\",\"value2\",\"value3\"]}}}", bodyJSON) -} - -func Test_TermsArray_method_should_create_termsType(t *testing.T) { - // Given - b := es.TermsArray("key", []any{"value1", "value2", "value3"}) - - // Then - assert.NotNil(t, b) - assert.IsTypeString(t, "es.termsType", b) -} - -//// TermsFunc //// - -func Test_TermsFunc_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.TermsFunc[string]) -} - -func Test_TermsFunc_should_create_json_with_terms_field_inside_query(t *testing.T) { - // Given - query := es.NewQuery( - es.TermsFunc("key", []string{"a", "b", "c"}, func(key string, values []string) bool { - return true - }), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"terms\":{\"key\":[\"a\",\"b\",\"c\"]}}}", bodyJSON) -} - -func Test_TermsFunc_should_not_add_terms_field_inside_query_when_callback_result_is_false(t *testing.T) { - // Given - query := es.NewQuery( - es.TermsFunc("key", []string{"a", "b", "c"}, func(key string, value []string) bool { - return false - }), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{}}", bodyJSON) -} - -func Test_TermsFunc_should_add_only_terms_fields_inside_the_query_when_callback_result_is_true(t *testing.T) { - // Given - query := es.NewQuery( - es.Bool(). - Filter( - es.TermsFunc("a", []string{"10", "11", "12"}, func(key string, value []string) bool { - return false - }), - es.TermsFunc("c", []string{"20", "21", "22"}, func(key string, value []string) bool { - return false - }), - es.TermsFunc("e", []string{"30", "31", "32"}, func(key string, value []string) bool { - return true - }), - ), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"bool\":{\"filter\":[{\"terms\":{\"e\":[\"30\",\"31\",\"32\"]}}]}}}", bodyJSON) -} - -func Test_TermsFunc_method_should_create_termType(t *testing.T) { - // Given - b := es.TermsFunc("key", []string{"a", "b", "c"}, func(key string, value []string) bool { - return true - }) - - // Then - assert.NotNil(t, b) - assert.IsTypeString(t, "es.termsType", b) -} - -//// TermsIf //// - -func Test_TermsIf_should_exist_on_es_package(t *testing.T) { - // Given When Then - assert.NotNil(t, es.TermsIf[string]) -} - -func Test_TermsIf_should_create_json_with_terms_field_inside_query(t *testing.T) { - // Given - query := es.NewQuery( - es.TermsIf("key", []string{"a", "b", "c"}, true), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"terms\":{\"key\":[\"a\",\"b\",\"c\"]}}}", bodyJSON) -} - -func Test_TermsIf_should_not_add_terms_field_inside_query_when_condition_is_false(t *testing.T) { - // Given - query := es.NewQuery( - es.TermsIf("key", []string{"a", "b", "c"}, false), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{}}", bodyJSON) -} - -func Test_TermsIf_should_add_only_terms_fields_inside_the_query_when_condition_is_true(t *testing.T) { - // Given - query := es.NewQuery( - es.Bool(). - Filter( - es.TermsIf("a", []string{"10", "11", "12"}, false), - es.TermsIf("c", []string{"20", "21", "22"}, false), - es.TermsIf("e", []string{"30", "31", "32"}, true), - ), - ) - - // When Then - assert.NotNil(t, query) - bodyJSON := assert.MarshalWithoutError(t, query) - assert.Equal(t, "{\"query\":{\"bool\":{\"filter\":[{\"terms\":{\"e\":[\"30\",\"31\",\"32\"]}}]}}}", bodyJSON) -} - -func Test_TermsIf_method_should_create_termType(t *testing.T) { - // Given - b := es.TermsIf("key", []string{"a", "b", "c"}, true) - - // Then - assert.NotNil(t, b) - assert.IsTypeString(t, "es.termsType", b) -} diff --git a/es/types.go b/es/types.go deleted file mode 100644 index b302f0f..0000000 --- a/es/types.go +++ /dev/null @@ -1,21 +0,0 @@ -package es - -import "unsafe" - -type Object map[string]any - -type Array []any - -func unsafeIsNil(x any) bool { - return (*[2]uintptr)(unsafe.Pointer(&x))[1] == 0 -} - -func correctType(b any) (any, bool) { - if b == nil || unsafeIsNil(b) { - return Object{}, false - } - if _, ok := b.(BoolType); ok { - return Object{"bool": b}, true - } - return b, true -} diff --git a/example/example.go b/example/example.go deleted file mode 100644 index 5a5000a..0000000 --- a/example/example.go +++ /dev/null @@ -1,104 +0,0 @@ -// nolint:all -package main - -import ( - "encoding/json" - "fmt" - "log" - - "github.com/Trendyol/es-query-builder/es" - "github.com/Trendyol/es-query-builder/es/enums/sort/order" -) - -func mockGetDocumentsEs(query string) (string, error) { - return fmt.Sprintf("query result for '%v'", query), nil -} - -func main() { - id := 42 - queryString, err := json.Marshal(buildQuery(id)) - if err != nil { - log.Fatal(err.Error()) - } - - documentsEs, err := mockGetDocumentsEs(string(queryString)) - if err != nil { - log.Fatal(err.Error()) - } - fmt.Printf("query result: %s\n", documentsEs) - - // Output: - // query result for '{"_source":{"includes":["id","type","indexedAt","chapters"]},"query":{"bool":{"filter":[{"terms":{"type":["DOC","FILE"]}}],"must":[{"bool":{"should":[{"term":{"doc.id":42}},{"term":{"file.fileId":42}}]}}]}},"size":45,"sort":[{"name":{"order":"asc"}}]}' - - // Formatted query string: - // { - // "_source": { - // "includes": [ - // "id", - // "type", - // "indexedAt", - // "chapters" - // ] - // }, - // "query": { - // "bool": { - // "filter": [ - // { - // "terms": { - // "type": [ - // "DOC", - // "FILE" - // ] - // } - // } - // ], - // "must": [ - // { - // "bool": { - // "should": [ - // { - // "term": { - // "doc.id": 42 - // } - // }, - // { - // "term": { - // "file.fileId": 42 - // } - // } - // ] - // } - // } - // ] - // } - // }, - // "size": 45, - // "sort": [ - // { - // "name": { - // "order": "asc" - // } - // } - // ] - // } -} - -func buildQuery(id int) es.Object { - query := es.NewQuery( - es.Bool(). - Must( - es.Bool(). - Should( - es.Term("doc.id", id), - es.Term("file.fileId", id), - ), - ). - Filter( - es.Terms("type", "DOC", "FILE"), - )). - Size(45). - Sort(es.Sort("name").Order(order.Asc)). - SourceIncludes("id", "type", "indexedAt", "chapters") - - return query -} diff --git a/go.mod b/go.mod deleted file mode 100644 index 0c7abaf..0000000 --- a/go.mod +++ /dev/null @@ -1,5 +0,0 @@ -module github.com/Trendyol/es-query-builder - -go 1.18 - -// No external dependencies 😎 diff --git a/internal/testing/constants/constants.go b/internal/testing/constants/constants.go deleted file mode 100644 index e3eab5f..0000000 --- a/internal/testing/constants/constants.go +++ /dev/null @@ -1,8 +0,0 @@ -package constants - -const ( - Zero = 0 - True = "true" - StatusOK = 200 - TestIndex = "foo-index" -) diff --git a/internal/testing/container/elasticsearch.go b/internal/testing/container/elasticsearch.go deleted file mode 100644 index 2ebfd17..0000000 --- a/internal/testing/container/elasticsearch.go +++ /dev/null @@ -1,84 +0,0 @@ -package container - -import ( - "context" - "fmt" - "runtime" - - "github.com/docker/go-connections/nat" - "github.com/testcontainers/testcontainers-go" - "github.com/testcontainers/testcontainers-go/wait" -) - -const ( - ElasticsearchImage = "docker.elastic.co/elasticsearch/elasticsearch:8.15.0" - defaultPort = "9200" -) - -type ElasticsearchContainer struct { - address string - ip string - port nat.Port - container testcontainers.Container - containerRequest testcontainers.ContainerRequest -} - -func NewContainer(image string) *ElasticsearchContainer { - req := testcontainers.ContainerRequest{ - Image: image, - ExposedPorts: []string{fmt.Sprintf("%s:%s", defaultPort, defaultPort)}, - Env: map[string]string{ - "cluster.name": "testcontainers-go", - "discovery.type": "single-node", - "bootstrap.memory_lock": "true", - "xpack.security.enabled": "false", // Disable security features (including TLS) - "xpack.security.http.ssl.enabled": "false", // Disable HTTPS for the HTTP API - "ES_JAVA_OPTS": "-Xms1g -Xmx1g", - }, - WaitingFor: wait.ForLog("up and running"), - } - return &ElasticsearchContainer{ - containerRequest: req, - } -} - -func (c *ElasticsearchContainer) Run() (err error) { - c.container, err = testcontainers.GenericContainer(context.Background(), testcontainers.GenericContainerRequest{ - ContainerRequest: c.containerRequest, - Started: true, - }) - if err != nil { - return err - } - - c.ip, err = c.container.Host(context.Background()) - if err != nil { - return err - } - c.port, err = c.container.MappedPort(context.Background(), defaultPort) - if err != nil { - return err - } - - if isRunningOnOSX() { - c.ip = "127.0.0.1" - } - - return nil -} - -func (c *ElasticsearchContainer) TerminateContainer() (err error) { - if c.container != nil { - return c.container.Terminate(context.Background()) - } - - return nil -} - -func (c *ElasticsearchContainer) Host() string { - return fmt.Sprintf("http://%s:%s", c.ip, c.port.Port()) -} - -func isRunningOnOSX() bool { - return runtime.GOOS == "darwin" -} diff --git a/internal/testing/elasticsearch_repository.go b/internal/testing/elasticsearch_repository.go deleted file mode 100644 index 7b534a8..0000000 --- a/internal/testing/elasticsearch_repository.go +++ /dev/null @@ -1,175 +0,0 @@ -package testing - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "strings" - - "github.com/elastic/go-elasticsearch/v8" - "github.com/elastic/go-elasticsearch/v8/esapi" - - "integration-tests/constants" -) - -type elasticsearchRepository struct { - client *elasticsearch.Client -} - -type ElasticsearchRepository interface { - Search(query string) ([]FooDocument, error) - BulkInsert(documents []FooDocument) error - Insert(document FooDocument) error - BulkDelete(docIds []string) error - Delete(docId string) error - DeleteByQuery(query string) error - Exists(docId string) bool -} - -func NewElasticsearchRepository(client *elasticsearch.Client) ElasticsearchRepository { - return &elasticsearchRepository{client: client} -} - -func (e *elasticsearchRepository) Search(query string) ([]FooDocument, error) { - res, err := e.client.Search( - e.client.Search.WithIndex(constants.TestIndex), - e.client.Search.WithBody(strings.NewReader(query)), - ) - defer func() { - if err = res.Body.Close(); err != nil { - panic(err) - } - }() - if err != nil { - return nil, fmt.Errorf("failed to execute search request: %w", err) - } - if res.StatusCode != http.StatusOK { - return nil, fmt.Errorf("unexpected status code %d: %s", res.StatusCode, res.String()) - } - - var searchResponse SearchResponse - if err = json.NewDecoder(res.Body).Decode(&searchResponse); err != nil { - return nil, fmt.Errorf("failed to decode search response: %w", err) - } - if len(searchResponse.Hits.Hits) == constants.Zero { - return nil, nil - } - - result := make([]FooDocument, 0) - for i := range searchResponse.Hits.Hits { - result = append(result, searchResponse.Hits.Hits[i].Source) - } - - return result, nil -} - -func (e *elasticsearchRepository) BulkInsert(documents []FooDocument) error { - var bulkRequestBody strings.Builder - - for i := range documents { - meta := fmt.Sprintf(`{"index":{"_index":"%s","_id":"%s"}}%s`, constants.TestIndex, documents[i].Id, "\n") - bulkRequestBody.WriteString(meta) - - docJson, err := json.Marshal(documents[i]) - if err != nil { - return fmt.Errorf("failed to marshal document with Id %s: %w", documents[i].Id, err) - } - bulkRequestBody.WriteString(string(docJson) + "\n") - } - request := esapi.BulkRequest{ - Body: strings.NewReader(bulkRequestBody.String()), - Refresh: constants.True, - } - - res, err := request.Do(context.Background(), e.client) - if err != nil { - return fmt.Errorf("failed to execute bulk insert request: %w", err) - } - if res.IsError() { - return fmt.Errorf("bulk insert request returned error: %s", res.String()) - } - return nil -} - -func (e *elasticsearchRepository) Insert(document FooDocument) error { - fooDoc, _ := json.Marshal(document) - - request := esapi.IndexRequest{ - Index: constants.TestIndex, - DocumentID: document.Id, - Body: strings.NewReader(string(fooDoc)), - Refresh: constants.True, - } - - res, err := request.Do(context.Background(), e.client) - if err != nil { - return fmt.Errorf("failed to execute insert request: %w", err) - } - if res.IsError() { - return fmt.Errorf("insert request returned error: %s", res.String()) - } - return err -} - -func (e *elasticsearchRepository) Delete(docId string) error { - request := esapi.DeleteRequest{ - Index: constants.TestIndex, - DocumentID: docId, - } - res, err := request.Do(context.Background(), e.client) - if err != nil { - return fmt.Errorf("failed to execute delete request: %w", err) - } - if res.IsError() { - return fmt.Errorf("delete request returned error: %s", res.String()) - } - return err -} - -func (e *elasticsearchRepository) BulkDelete(docIds []string) error { - var bulkRequestBody strings.Builder - - for _, docId := range docIds { - meta := fmt.Sprintf(`{"delete":{"_index":"%s","_id":"%s"}}%s`, constants.TestIndex, docId, "\n") - bulkRequestBody.WriteString(meta) - } - - request := esapi.BulkRequest{ - Body: strings.NewReader(bulkRequestBody.String()), - Refresh: constants.True, - } - - res, err := request.Do(context.Background(), e.client) - if err != nil { - return fmt.Errorf("failed to execute bulk delete request: %w", err) - } - if res.IsError() { - return fmt.Errorf("bulk delete request returned error: %s", res.String()) - } - return nil -} - -func (e *elasticsearchRepository) DeleteByQuery(query string) error { - request := esapi.DeleteByQueryRequest{ - Index: []string{constants.TestIndex}, - Body: strings.NewReader(query), - } - res, err := request.Do(context.Background(), e.client) - if err != nil { - return fmt.Errorf("failed to execute delete by query request: %w", err) - } - if res.IsError() { - return fmt.Errorf("delete by query request returned error: %s", res.String()) - } - return err -} - -func (e *elasticsearchRepository) Exists(docId string) bool { - request := esapi.ExistsRequest{ - Index: constants.TestIndex, - DocumentID: docId, - } - res, _ := request.Do(context.Background(), e.client) - return res.StatusCode == constants.StatusOK -} diff --git a/internal/testing/go.mod b/internal/testing/go.mod deleted file mode 100644 index 8ae4746..0000000 --- a/internal/testing/go.mod +++ /dev/null @@ -1,64 +0,0 @@ -module integration-tests - -go 1.22 - -replace github.com/Trendyol/es-query-builder => ./../.. - -require ( - github.com/Trendyol/es-query-builder v0.2.0 - github.com/bayraktugrul/go-await v1.1.1 - github.com/docker/go-connections v0.5.0 - github.com/elastic/elastic-transport-go/v8 v8.6.0 - github.com/elastic/go-elasticsearch/v8 v8.15.0 - github.com/stretchr/testify v1.9.0 - github.com/testcontainers/testcontainers-go v0.33.0 -) - -require ( - dario.cat/mergo v1.0.0 // indirect - github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect - github.com/Microsoft/go-winio v0.6.2 // indirect - github.com/cenkalti/backoff/v4 v4.2.1 // indirect - github.com/containerd/containerd v1.7.18 // indirect - github.com/containerd/log v0.1.0 // indirect - github.com/containerd/platforms v0.2.1 // indirect - github.com/cpuguy83/dockercfg v0.3.1 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect - github.com/distribution/reference v0.6.0 // indirect - github.com/docker/docker v27.1.1+incompatible // indirect - github.com/docker/go-units v0.5.0 // indirect - github.com/felixge/httpsnoop v1.0.4 // indirect - github.com/go-logr/logr v1.4.1 // indirect - github.com/go-logr/stdr v1.2.2 // indirect - github.com/go-ole/go-ole v1.2.6 // indirect - github.com/gogo/protobuf v1.3.2 // indirect - github.com/google/uuid v1.6.0 // indirect - github.com/klauspost/compress v1.17.4 // indirect - github.com/kr/text v0.1.0 // indirect - github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect - github.com/magiconair/properties v1.8.7 // indirect - github.com/moby/docker-image-spec v1.3.1 // indirect - github.com/moby/patternmatcher v0.6.0 // indirect - github.com/moby/sys/sequential v0.5.0 // indirect - github.com/moby/sys/user v0.1.0 // indirect - github.com/moby/term v0.5.0 // indirect - github.com/morikuni/aec v1.0.0 // indirect - github.com/opencontainers/go-digest v1.0.0 // indirect - github.com/opencontainers/image-spec v1.1.0 // indirect - github.com/pkg/errors v0.9.1 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect - github.com/shirou/gopsutil/v3 v3.23.12 // indirect - github.com/shoenig/go-m1cpu v0.1.6 // indirect - github.com/sirupsen/logrus v1.9.3 // indirect - github.com/tklauser/go-sysconf v0.3.12 // indirect - github.com/tklauser/numcpus v0.6.1 // indirect - github.com/yusufpapurcu/wmi v1.2.3 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 // indirect - go.opentelemetry.io/otel v1.24.0 // indirect - go.opentelemetry.io/otel/metric v1.24.0 // indirect - go.opentelemetry.io/otel/trace v1.24.0 // indirect - golang.org/x/crypto v0.31.0 // indirect - golang.org/x/sys v0.28.0 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect -) diff --git a/internal/testing/go.sum b/internal/testing/go.sum deleted file mode 100644 index 66dd263..0000000 --- a/internal/testing/go.sum +++ /dev/null @@ -1,197 +0,0 @@ -dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk= -dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk= -github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24 h1:bvDV9vkmnHYOMsOr4WLk+Vo07yKIzd94sVoIqshQ4bU= -github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8= -github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= -github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= -github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= -github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= -github.com/bayraktugrul/go-await v1.1.1 h1:ecNe3NhOoPQ2jEomimms++385uvFwFoFpO3gGapURbs= -github.com/bayraktugrul/go-await v1.1.1/go.mod h1:+YPkaRay7p91FGPcL/JVzYuPnvaE8ABhc/etCt9UYTw= -github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM= -github.com/cenkalti/backoff/v4 v4.2.1/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= -github.com/containerd/containerd v1.7.18 h1:jqjZTQNfXGoEaZdW1WwPU0RqSn1Bm2Ay/KJPUuO8nao= -github.com/containerd/containerd v1.7.18/go.mod h1:IYEk9/IO6wAPUz2bCMVUbsfXjzw5UNP5fLz4PsUygQ4= -github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= -github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= -github.com/containerd/platforms v0.2.1 h1:zvwtM3rz2YHPQsF2CHYM8+KtB5dvhISiXh5ZpSBQv6A= -github.com/containerd/platforms v0.2.1/go.mod h1:XHCb+2/hzowdiut9rkudds9bE5yJ7npe7dG/wG+uFPw= -github.com/cpuguy83/dockercfg v0.3.1 h1:/FpZ+JaygUR/lZP2NlFI2DVfrOEMAIKP5wWEJdoYe9E= -github.com/cpuguy83/dockercfg v0.3.1/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc= -github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= -github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= -github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= -github.com/docker/docker v27.1.1+incompatible h1:hO/M4MtV36kzKldqnA37IWhebRA+LnqqcqDja6kVaKY= -github.com/docker/docker v27.1.1+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= -github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c= -github.com/docker/go-connections v0.5.0/go.mod h1:ov60Kzw0kKElRwhNs9UlUHAE/F9Fe6GLaXnqyDdmEXc= -github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= -github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= -github.com/elastic/elastic-transport-go/v8 v8.6.0 h1:Y2S/FBjx1LlCv5m6pWAF2kDJAHoSjSRSJCApolgfthA= -github.com/elastic/elastic-transport-go/v8 v8.6.0/go.mod h1:YLHer5cj0csTzNFXoNQ8qhtGY1GTvSqPnKWKaqQE3Hk= -github.com/elastic/go-elasticsearch/v8 v8.15.0 h1:IZyJhe7t7WI3NEFdcHnf6IJXqpRf+8S8QWLtZYYyBYk= -github.com/elastic/go-elasticsearch/v8 v8.15.0/go.mod h1:HCON3zj4btpqs2N1jjsAy4a/fiAul+YBP00mBH4xik8= -github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= -github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= -github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ= -github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= -github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= -github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= -github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= -github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= -github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= -github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= -github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= -github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.16.0 h1:YBftPWNWd4WwGqtY2yeZL2ef8rHAxPBD8KFhJpmcqms= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.16.0/go.mod h1:YN5jB8ie0yfIUg6VvR9Kz84aCaG7AsGZnLjhHbUqwPg= -github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= -github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.17.4 h1:Ej5ixsIri7BrIjBkRZLTo6ghwrEtHFk7ijlczPW4fZ4= -github.com/klauspost/compress v1.17.4/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM= -github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= -github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4= -github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I= -github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= -github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= -github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= -github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= -github.com/moby/patternmatcher v0.6.0 h1:GmP9lR19aU5GqSSFko+5pRqHi+Ohk1O69aFiKkVGiPk= -github.com/moby/patternmatcher v0.6.0/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc= -github.com/moby/sys/sequential v0.5.0 h1:OPvI35Lzn9K04PBbCLW0g4LcFAJgHsvXsRyewg5lXtc= -github.com/moby/sys/sequential v0.5.0/go.mod h1:tH2cOOs5V9MlPiXcQzRC+eEyab644PWKGRYaaV5ZZlo= -github.com/moby/sys/user v0.1.0 h1:WmZ93f5Ux6het5iituh9x2zAG7NFY9Aqi49jjE1PaQg= -github.com/moby/sys/user v0.1.0/go.mod h1:fKJhFOnsCN6xZ5gSfbM6zaHGgDJMrqt9/reuj4T7MmU= -github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0= -github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= -github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= -github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= -github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= -github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= -github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug= -github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c h1:ncq/mPwQF4JjgDlrVEn3C11VoGHZN7m8qihwgMEtzYw= -github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= -github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XFkP+Eg= -github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= -github.com/shirou/gopsutil/v3 v3.23.12 h1:z90NtUkp3bMtmICZKpC4+WaknU1eXtp5vtbQ11DgpE4= -github.com/shirou/gopsutil/v3 v3.23.12/go.mod h1:1FrWgea594Jp7qmjHUUPlJDTPgcsb9mGnXDxavtikzM= -github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM= -github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ= -github.com/shoenig/test v0.6.4 h1:kVTaSd7WLz5WZ2IaoM0RSzRsUD+m8wRR+5qvntpn4LU= -github.com/shoenig/test v0.6.4/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnjqq0k= -github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= -github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= -github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= -github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/testcontainers/testcontainers-go v0.33.0 h1:zJS9PfXYT5O0ZFXM2xxXfk4J5UMw/kRiISng037Gxdw= -github.com/testcontainers/testcontainers-go v0.33.0/go.mod h1:W80YpTa8D5C3Yy16icheD01UTDu+LmXIA2Keo+jWtT8= -github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFAEVmqU= -github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI= -github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+Fk= -github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY= -github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yusufpapurcu/wmi v1.2.3 h1:E1ctvB7uKFMOJw3fdOW32DwGE9I7t++CRUEMKvFoFiw= -github.com/yusufpapurcu/wmi v1.2.3/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 h1:jq9TW8u3so/bN+JPT166wjOI6/vQPF6Xe7nMNIltagk= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0/go.mod h1:p8pYQP+m5XfbZm9fxtSKAbM6oIllS7s2AfxrChvc7iw= -go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo= -go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.19.0 h1:Mne5On7VWdx7omSrSSZvM4Kw7cS7NQkOOmLcgscI51U= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.19.0/go.mod h1:IPtUMKL4O3tH5y+iXVyAXqpAwMuzC1IrxVS81rummfE= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.19.0 h1:IeMeyr1aBvBiPVYihXIaeIZba6b8E1bYp7lbdxK8CQg= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.19.0/go.mod h1:oVdCUtjq9MK9BlS7TtucsQwUcXcymNiEDjgDD2jMtZU= -go.opentelemetry.io/otel/metric v1.24.0 h1:6EhoGWWK28x1fbpA4tYTOWBkPefTDQnb8WSGXlc88kI= -go.opentelemetry.io/otel/metric v1.24.0/go.mod h1:VYhLe1rFfxuTXLgj4CBiyz+9WYBA8pNGJgDcSFRKBco= -go.opentelemetry.io/otel/sdk v1.21.0 h1:FTt8qirL1EysG6sTQRZ5TokkU8d0ugCj8htOgThZXQ8= -go.opentelemetry.io/otel/sdk v1.21.0/go.mod h1:Nna6Yv7PWTdgJHVRD9hIYywQBRx7pbox6nwBnZIxl/E= -go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y1YELI= -go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU= -go.opentelemetry.io/proto/otlp v1.0.0 h1:T0TX0tmXU8a3CbNXzEKGeU5mIVOdf0oykP+u2lIVU/I= -go.opentelemetry.io/proto/otlp v1.0.0/go.mod h1:Sy6pihPLfYHkr3NkUbEhGHFhINUSI/v80hjKIs5JXpM= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= -golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= -golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs= -golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= -golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q= -golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= -golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= -golang.org/x/time v0.0.0-20220210224613-90d013bbcef8 h1:vVKdlvoWBphwdxWKrFZEuM0kGgGLxUOYcY4U/2Vjg44= -golang.org/x/time v0.0.0-20220210224613-90d013bbcef8/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/genproto v0.0.0-20230920204549-e6e6cdab5c13 h1:vlzZttNJGVqTsRFU9AmdnrcO1Znh8Ew9kCD//yjigk0= -google.golang.org/genproto/googleapis/api v0.0.0-20230913181813-007df8e322eb h1:lK0oleSc7IQsUxO3U5TjL9DWlsxpEBemh+zpB7IqhWI= -google.golang.org/genproto/googleapis/api v0.0.0-20230913181813-007df8e322eb/go.mod h1:KjSP20unUpOx5kyQUFa7k4OJg0qeJ7DEZflGDu2p6Bk= -google.golang.org/genproto/googleapis/rpc v0.0.0-20231002182017-d307bd883b97 h1:6GQBEOdGkX6MMTLT9V+TjtIRZCw9VPD5Z+yHY9wMgS0= -google.golang.org/genproto/googleapis/rpc v0.0.0-20231002182017-d307bd883b97/go.mod h1:v7nGkzlmW8P3n/bKmWBn2WpBjpOEx8Q6gMueudAmKfY= -google.golang.org/grpc v1.64.1 h1:LKtvyfbX3UGVPFcGqJ9ItpVWW6oN/2XqTxfAnwRRXiA= -google.golang.org/grpc v1.64.1/go.mod h1:hiQF4LFZelK2WKaP6W0L92zGHtiQdZxk8CrSdvyjeP0= -google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= -google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU= -gotest.tools/v3 v3.5.1/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU= diff --git a/internal/testing/query_string_test.go b/internal/testing/query_string_test.go deleted file mode 100644 index 69a8e29..0000000 --- a/internal/testing/query_string_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package testing - -import ( - "encoding/json" - - "github.com/Trendyol/es-query-builder/es" - "github.com/bayraktugrul/go-await" - "github.com/stretchr/testify/assert" -) - -func (s *testSuite) Test_it_should_return_documents_that_filtered_by_query_string_with_wildcard_or_operator() { - // Given - foo := FooDocument{ - Id: "10", - Foo: "foo", - } - bar := FooDocument{ - Id: "20", - Foo: "bar", - } - george := FooDocument{ - Id: "30", - Foo: "george orwell", - } - s.ElasticsearchRepository.BulkInsert([]FooDocument{foo, bar, george}) - await.New().Await(func() bool { return s.ElasticsearchRepository.Exists(foo.Id) }) - await.New().Await(func() bool { return s.ElasticsearchRepository.Exists(bar.Id) }) - await.New().Await(func() bool { return s.ElasticsearchRepository.Exists(george.Id) }) - - query := es.NewQuery( - es.Bool().Must( - es.QueryString[string]("ge* OR bar").AnalyzeWildcard(true)), - ) - bodyJSON, _ := json.Marshal(query) - - // When - result, err := s.ElasticsearchRepository.Search(string(bodyJSON)) - - // Then - assert.Nil(s.T(), err) - assert.Equal(s.T(), len(result), 2) - assert.Equal(s.T(), result[0].Foo, "george orwell") - assert.Equal(s.T(), result[1].Foo, "bar") - - s.ElasticsearchRepository.BulkDelete([]string{foo.Id, bar.Id, george.Id}) -} diff --git a/internal/testing/regexp_query_test.go b/internal/testing/regexp_query_test.go deleted file mode 100644 index 497b5f2..0000000 --- a/internal/testing/regexp_query_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package testing - -import ( - "encoding/json" - "github.com/Trendyol/es-query-builder/es" - "github.com/bayraktugrul/go-await" - "github.com/stretchr/testify/assert" -) - -func (s *testSuite) Test_it_should_return_documents_that_filtered_by_regexp_query() { - // Given - foo := FooDocument{ - Id: "10", - Foo: "foo", - } - bar := FooDocument{ - Id: "20", - Foo: "bar", - } - georgeOrwell := FooDocument{ - Id: "30", - Foo: "george orwell", - } - georgeBest := FooDocument{ - Id: "40", - Foo: "george best", - } - - s.ElasticsearchRepository.BulkInsert([]FooDocument{foo, bar, georgeOrwell, georgeBest}) - await.New().Await(func() bool { return s.ElasticsearchRepository.Exists(foo.Id) }) - await.New().Await(func() bool { return s.ElasticsearchRepository.Exists(bar.Id) }) - await.New().Await(func() bool { return s.ElasticsearchRepository.Exists(georgeOrwell.Id) }) - await.New().Await(func() bool { return s.ElasticsearchRepository.Exists(georgeBest.Id) }) - - //f* OR bar - query := es.NewQuery( - es.Regexp("foo", "george.*"), - ) - bodyJSON, _ := json.Marshal(query) - - // When - result, err := s.ElasticsearchRepository.Search(string(bodyJSON)) - - // Then - assert.Nil(s.T(), err) - assert.Equal(s.T(), len(result), 2) - assert.Equal(s.T(), result[0].Foo, "george orwell") - assert.Equal(s.T(), result[1].Foo, "george best") - - s.ElasticsearchRepository.BulkDelete([]string{foo.Id, bar.Id, georgeOrwell.Id, georgeBest.Id}) -} diff --git a/internal/testing/search_response.go b/internal/testing/search_response.go deleted file mode 100644 index 98ee27e..0000000 --- a/internal/testing/search_response.go +++ /dev/null @@ -1,18 +0,0 @@ -package testing - -type FooDocument struct { - Id string `json:"id"` - Foo string `json:"foo"` -} - -type Hit struct { - Source FooDocument `json:"_source"` -} - -type Hits struct { - Hits []Hit `json:"hits"` -} - -type SearchResponse struct { - Hits Hits `json:"hits"` -} diff --git a/internal/testing/simple_query_string_test.go b/internal/testing/simple_query_string_test.go deleted file mode 100644 index e825923..0000000 --- a/internal/testing/simple_query_string_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package testing - -import ( - "encoding/json" - - "github.com/Trendyol/es-query-builder/es" - "github.com/bayraktugrul/go-await" - "github.com/stretchr/testify/assert" -) - -func (s *testSuite) Test_it_should_return_documents_that_filtered_by_simple_query_string_with_wildcard_or_operator() { - // Given - foo := FooDocument{ - Id: "10", - Foo: "foo", - } - bar := FooDocument{ - Id: "20", - Foo: "bar", - } - george := FooDocument{ - Id: "30", - Foo: "george orwell", - } - s.ElasticsearchRepository.BulkInsert([]FooDocument{foo, bar, george}) - await.New().Await(func() bool { return s.ElasticsearchRepository.Exists(foo.Id) }) - await.New().Await(func() bool { return s.ElasticsearchRepository.Exists(bar.Id) }) - await.New().Await(func() bool { return s.ElasticsearchRepository.Exists(george.Id) }) - - query := es.NewQuery( - es.Bool().Must( - es.SimpleQueryString[string]("ge* OR bar").AnalyzeWildcard(true)), - ) - bodyJSON, _ := json.Marshal(query) - - // When - result, err := s.ElasticsearchRepository.Search(string(bodyJSON)) - - // Then - assert.Nil(s.T(), err) - assert.Equal(s.T(), len(result), 2) - assert.Equal(s.T(), result[0].Foo, "bar") - assert.Equal(s.T(), result[1].Foo, "george orwell") - - s.ElasticsearchRepository.BulkDelete([]string{foo.Id, bar.Id, george.Id}) -} diff --git a/internal/testing/suite_test.go b/internal/testing/suite_test.go deleted file mode 100644 index 9fbc363..0000000 --- a/internal/testing/suite_test.go +++ /dev/null @@ -1,93 +0,0 @@ -package testing - -import ( - "context" - "fmt" - "os" - "strings" - "testing" - - "github.com/elastic/elastic-transport-go/v8/elastictransport" - "github.com/elastic/go-elasticsearch/v8" - "github.com/elastic/go-elasticsearch/v8/esapi" - "github.com/stretchr/testify/suite" - - "integration-tests/constants" - "integration-tests/container" -) - -func TestSuite(t *testing.T) { - suite.Run(t, new(testSuite)) -} - -type testSuite struct { - suite.Suite - ElasticContainer *container.ElasticsearchContainer - ESClient *elasticsearch.Client - ElasticsearchRepository ElasticsearchRepository -} - -func (s *testSuite) SetupSuite() { - s.ElasticContainer = container.NewContainer(container.ElasticsearchImage) - err := s.ElasticContainer.Run() - if err != nil { - fmt.Println(fmt.Printf("error starting elasticsearch container. err %v", err)) - s.T().FailNow() - } - - cfg := elasticsearch.Config{ - Addresses: []string{s.ElasticContainer.Host()}, - Logger: &elastictransport.ColorLogger{ - Output: os.Stdout, - }, - DiscoverNodesOnStart: false, - } - s.ESClient, err = elasticsearch.NewClient(cfg) - s.ElasticsearchRepository = NewElasticsearchRepository(s.ESClient) - - indicesRequest := esapi.IndicesCreateRequest{ - Index: constants.TestIndex, - Body: strings.NewReader(testIndexBody()), - } - - _, err = indicesRequest.Do(context.Background(), s.ESClient) - if err != nil { - fmt.Println(fmt.Printf("error creating index. err %v", err)) - s.T().FailNow() - } -} - -func (s *testSuite) TearDownSuite() { - err := s.ElasticContainer.TerminateContainer() - if err != nil { - s.T().FailNow() - } -} - -func testIndexBody() string { - return `{ - "settings": { - "index": { - "refresh_interval": "1ms", - "number_of_shards": "1", - "number_of_replicas": "1", - "max_result_window": "50000", - "max_terms_count": "100" - } - }, - "mappings": { - "properties": { - "foo": { - "type": "keyword" - }, - "meta": { - "properties": { - "id": { - "type": "keyword" - } - } - } - } - } - }` -} diff --git a/internal/testing/term_query_test.go b/internal/testing/term_query_test.go deleted file mode 100644 index e33dd5b..0000000 --- a/internal/testing/term_query_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package testing - -import ( - "encoding/json" - - "github.com/Trendyol/es-query-builder/es" - "github.com/bayraktugrul/go-await" - "github.com/stretchr/testify/assert" -) - -func (s *testSuite) Test_it_should_return_documents_that_filtered_by_term_query() { - // Given - foo := FooDocument{ - Id: "10", - Foo: "foo", - } - bar := FooDocument{ - Id: "20", - Foo: "bar", - } - - s.ElasticsearchRepository.BulkInsert([]FooDocument{foo, bar}) - await.New().Await(func() bool { return s.ElasticsearchRepository.Exists(foo.Id) }) - await.New().Await(func() bool { return s.ElasticsearchRepository.Exists(bar.Id) }) - - query := es.NewQuery( - es.Bool().Must( - es.Term("foo", "foo")), - ) - bodyJSON, _ := json.Marshal(query) - - // When - result, err := s.ElasticsearchRepository.Search(string(bodyJSON)) - - // Then - assert.Nil(s.T(), err) - assert.Equal(s.T(), len(result), 1) - assert.Equal(s.T(), result[0].Foo, "foo") - - s.ElasticsearchRepository.BulkDelete([]string{foo.Id, bar.Id}) -} diff --git a/internal/testing/terms_query_test.go b/internal/testing/terms_query_test.go deleted file mode 100644 index c42c1db..0000000 --- a/internal/testing/terms_query_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package testing - -import ( - "encoding/json" - - "github.com/Trendyol/es-query-builder/es" - "github.com/bayraktugrul/go-await" - "github.com/stretchr/testify/assert" -) - -func (s *testSuite) Test_it_should_return_documents_that_filtered_by_terms_query() { - // Given - doc1 := FooDocument{ - Id: "10", - Foo: "foo", - } - doc2 := FooDocument{ - Id: "20", - Foo: "mars", - } - doc3 := FooDocument{ - Id: "30", - Foo: "earth", - } - - s.ElasticsearchRepository.BulkInsert([]FooDocument{doc1, doc2, doc3}) - await.New().Await(func() bool { return s.ElasticsearchRepository.Exists(doc1.Id) }) - await.New().Await(func() bool { return s.ElasticsearchRepository.Exists(doc2.Id) }) - await.New().Await(func() bool { return s.ElasticsearchRepository.Exists(doc3.Id) }) - - query := es.NewQuery( - es.Bool().Must( - es.Terms("foo", "earth", "mars")), - ) - bodyJSON, _ := json.Marshal(query) - - // When - result, err := s.ElasticsearchRepository.Search(string(bodyJSON)) - - // Then - assert.Nil(s.T(), err) - assert.Equal(s.T(), len(result), 2) - assert.Contains(s.T(), result, doc2) - assert.Contains(s.T(), result, doc3) - - s.ElasticsearchRepository.BulkDelete([]string{doc1.Id, doc2.Id, doc3.Id}) -} diff --git a/test/assert/assert.go b/test/assert/assert.go deleted file mode 100644 index 674bd24..0000000 --- a/test/assert/assert.go +++ /dev/null @@ -1,96 +0,0 @@ -package assert - -import ( - "encoding/json" - "fmt" - "reflect" - "strings" -) - -type TestingT interface { - Errorf(format string, args ...interface{}) -} - -func MarshalWithoutError(t TestingT, body any) string { - marshal, err := json.Marshal(body) - if err != nil { - t.Errorf("marshal error: '%s'", err.Error()) - } - return string(marshal) -} - -func Equal(t TestingT, expected, actual any, messages ...string) { - message := getMessages(messages) - if !reflect.DeepEqual(expected, actual) { - t.Errorf("\nExpected: '%v' type: <%s>\nActual: '%v' type: <%s>. %s", - expected, reflect.TypeOf(expected).String(), actual, reflect.TypeOf(actual).String(), message) - } -} - -func EqualReference(t TestingT, expected, actual any, messages ...string) { - message := getMessages(messages) - expectedPointer, actualPointer := reflect.ValueOf(expected).Pointer(), reflect.ValueOf(actual).Pointer() - if !(expectedPointer == actualPointer) { - t.Errorf("\nExpected: '%v', Actual: '%v'. %s", expectedPointer, actualPointer, message) - } -} - -func NotEqualReference(t TestingT, expected, actual any, messages ...string) { - message := getMessages(messages) - expectedPointer, actualPointer := reflect.ValueOf(expected).Pointer(), reflect.ValueOf(actual).Pointer() - if expectedPointer == actualPointer { - t.Errorf("Expected and Actual have the same reference: '%v'. %s", expectedPointer, message) - } -} - -func True(t TestingT, condition bool, messages ...string) { - message := getMessages(messages) - if !condition { - t.Errorf("Expected: true, Actual: false. %s", message) - } -} - -func False(t TestingT, condition bool, messages ...string) { - message := getMessages(messages) - if condition { - t.Errorf("Expected: false, Actual: true. %s", message) - } -} - -func Nil(t TestingT, value any, messages ...string) { - message := getMessages(messages) - if value != nil { - t.Errorf("Expected: nil, Actual: '%v'. %s", value, message) - } -} - -func NotNil(t TestingT, value any, messages ...string) { - message := getMessages(messages) - if value == nil { - t.Errorf("Expected: not nil, Actual: nil. %s", message) - } -} - -func IsType(t TestingT, expected, actual any, messages ...string) { - message := getMessages(messages) - expectedType := reflect.TypeOf(expected) - actualValue := reflect.TypeOf(actual) - if expectedType != actualValue { - t.Errorf("Expected type '%v', but got type '%v'. %s", expectedType, actualValue, message) - } -} - -func IsTypeString(t TestingT, expectedType string, actual any, messages ...string) { - message := getMessages(messages) - actualValue := reflect.TypeOf(actual) - if expectedType != actualValue.String() { - t.Errorf("Expected type '%v', but got type '%v'. %s", expectedType, actualValue, message) - } -} - -func getMessages(messages []string) string { - if len(messages) > 0 { - return fmt.Sprintf("messages: %s", strings.Join(messages, " ")) - } - return "" -}