Skip to content

Provide a helper for reading selected fields from search response #8758

@DRKV333

Description

@DRKV333

Is your feature request related to a problem? Please describe.

Consider a search like this, that uses DocvalueFields:

SearchResponse<Dialog> search = await elasticClient.SearchAsync<Dialog>(s => s
    .Indices(Indices.Index<Dialog>())
    .Query(q => q
        .Match(m => m
            .Field(x => x.Text)
            .Query("hello")
        )
    )
    .Size(1)
    .Source(false)
    .DocvalueFields(
        f => f.Field(x => x.Ver)
    )
);

To get the actual value of this field from the response, I have to do something like this:

int ver = ((JsonElement)search.Hits.Single().Fields!["ver"])[0].GetInt32();

Which is not intuitive and very inconvenient.

Describe the solution you'd like

It would be great to have some sort of extension method, that would let me do this without all the weird casting and conversion. Maybe something like this:

int ver = search.Hits.Single().GetFieldValues(x => x.Ver).Single();

Describe alternatives you've considered

I have a helper like this in my own code:

private static readonly JsonSerializerOptions fieldValuesOptions = new() { NumberHandling = JsonNumberHandling.AllowReadingFromString };

public static IEnumerable<TField> GetFieldValues<TDoc, TField>(this Hit<TDoc> hit, Inferrer inferrer, Expression<Func<TDoc, TField>> expression) =>
    ((JsonElement)hit.Fields![inferrer.Field(expression)]).EnumerateArray().Select(x => x.Deserialize<TField>(fieldValuesOptions)!);

But I sill feel like this should not be this difficult to do, and there should be a builtin helper.

Additional context

This applies to other ways of selecting specific fields in the search query, such as "stored_fields" or "fields". (Though not _source filtering.) The only info I found about this subject is this really old Stack Overflow question, where all the answers seem to be completely outdated: https://stackoverflow.com/questions/23688365/load-specific-fields-in-elasticsearch-nest-query
So it might also be nice to write something about this in the documentation.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions