elastic / go-elasticsearch

The official Go client for Elasticsearch
https://github.com/elastic/go-elasticsearch#go-elasticsearch
Apache License 2.0
50 stars 617 forks source link

Trying Sort by Script. Kibana worked but GoLang failed on JSON parsing, "_script" #764

Closed 9tontruck closed 11 months ago

9tontruck commented 11 months ago

Previous thread: https://github.com/elastic/go-elasticsearch/issues/757

@Anaethelion Thanks for your comment in my previous thread. I updated my ES client so my app is using "github.com/elastic/go-elasticsearch/v7/esapi" as you suggested And my search function is something like this now:

func (e ElasticSearchClient) Search(ctx context.Context,
    index string,
    searchType string,
    search map[string]interface{},
) (*esapi.Response, error) {
    jsonString, _ := json.Marshal(search)
    return e.es.Search(
        e.es.Search.WithContext(context.Background()),
        e.es.Search.WithIndex(index),
        e.es.Search.WithBody(strings.NewReader(string(jsonString))),
        e.es.Search.WithTrackTotalHits(true),
        e.es.Search.WithContext(ctx),
    )
}

Query:

{
  "query": {
    "bool" : {
      "must" : [
        {
          "term" : { "latestEvent" : "AAA" }
        },
        {
          "range" : {
          "latestEventDate" : { "gte" : "2023-11-10T17:40:50.07Z" }
          }
        }
      ]
    }
  },
  "sort": [
    {
      "_script": {
        "type": "number",
        "order": "desc",
        "script": {
          "source": """
            def value = {some kind of calculation}
            return value;
          """,
          "params": {
            "mean": 1,
            "sd": 2,
            "currentTimestamp": 1699943316141
          }
        }
      }

    }
  ],
  "_source": [
    "latestEvent",
    "latestEventDate"
  ]
}

But I am still having JSON parsing errors when I add _script inside of the Sort field. ref- https://www.elastic.co/guide/en/elasticsearch/reference/6.4/search-request-sort.html#_script_based_sorting

The version of my ElasticSearch is 6.4

Would you guide me to use scrip-sort using the go-elasticsearch client?

Anaethelion commented 11 months ago

Hi @9tontruck

Sorry for the late reply.

Right off the bat, what I'd suggest would be to remove the multiline string you have in the source field, just use a plain string to represent your script.