Skip to content

How to send doc fields as parameter to the script? #3

Description

@DaiZack

Is it possible to send doc fields as parameter to the script?
e.g

PUT _scripts/levenshtein
{
  "script": {
    "lang": "painless",
    "source": """
      String a = params.a;
      String b = params.b;

      int[][] dp = new int[a.length() + 1][b.length() + 1];

      for (int i = 0; i <= a.length(); i++) {
        for (int j = 0; j <= b.length(); j++) {
          if (i == 0) {
            dp[i][j] = j;
          } else if (j == 0) {
            dp[i][j] = i;
          } else {
            int cost = a.charAt(i - 1) == b.charAt(j - 1) ? 0 : 1;
            int deletion = dp[i - 1][j] + 1;
            int insertion = dp[i][j - 1] + 1;
            int substitution = dp[i - 1][j - 1] + cost;
            int tempMin = (int) Math.min(deletion, insertion);
            dp[i][j] = (int) Math.min(tempMin, substitution);
          }
        }
      }

      int distance = dp[a.length()][b.length()];
      int maxLength = (int) Math.max(a.length(), b.length());
      return maxLength > 0 ? 1.0 - ((double) distance / (double) maxLength) : 0.0;
    """
  }
}

And use it dynamically

GET /duns_magic_v3_nj/_search
{
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "name_sim_score": {
      "script": {
        "id": "levenshtein",
        "params": {
          "a": "kitten xyz",
          "b": "doc['name'].value"
        }
      }
    },
    "city_sim_score": {
      "script": {
        "id": "levenshtein",
        "params": {
          "a": "kitten xyz",
          "b": "doc['city'].value"
        }
      }
    }
  }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions