Script Fields Usage

edit

Allows to return a script evaluation (based on different fields) for each hit.

Script fields can work on fields that are not stored, and allow to return custom values to be returned (the evaluated value of the script).

Script fields can also access the actual _source document and extract specific elements to be returned from it by using params['_source'].

Script fields can be accessed on the response using .Fields, similarly to stored fields.

See the Elasticsearch documentation on script fields for more detail.

Fluent DSL example

edit
s => s
.ScriptFields(sf => sf
    .ScriptField("test1", sc => sc
        .Source("doc['numberOfCommits'].value * 2")
    )
    .ScriptField("test2", sc => sc
        .Source("doc['numberOfCommits'].value * params.factor")
        .Params(p => p
            .Add("factor", 2.0)
        )
    )
)

Object Initializer syntax example

edit
new SearchRequest<Project>
{
    ScriptFields = new ScriptFields
    {
        { "test1", new ScriptField { Script = new InlineScript("doc['numberOfCommits'].value * 2") } },
        {
            "test2", new InlineScript("doc['numberOfCommits'].value * params.factor")
            {
                Params = new FluentDictionary<string, object>
                {
                    { "factor", 2.0 }
                }
            }
        }
    }
}

Example json output.

{
  "script_fields": {
    "test1": {
      "script": {
        "source": "doc['numberOfCommits'].value * 2"
      }
    },
    "test2": {
      "script": {
        "source": "doc['numberOfCommits'].value * params.factor",
        "params": {
          "factor": 2.0
        }
      }
    }
  }
}

Handling Responses

edit
foreach (var fields in response.Fields)
{
    fields.Value<int>("test1").Should().BeGreaterOrEqualTo(0);
    fields.Value<double>("test2").Should().BeGreaterOrEqualTo(0);
}