Search code examples
elasticsearchnest

How to understand source index in muilti-index NEST query?


I have two indices in my ElasticSearch, let's name them "trusted" and "untrusted". Both indices have the same template/fields/settings.

Based on some flag I perform a NEST query to one or both indices.

var indices = request.IncludeUntrustedSources
            ? new[] {"trusted", "untrusted"}
            : new[] {"trusted"};

var searchResponse = await _client.SearchAsync<SearchResultItem>(c => c
    .Query(q => q.Bool(_ => query))
    .Index(indices)
    .Sort(ss => ss
         .Descending(SortSpecialField.Score))
    .From(skip)
    .Size(perPage)

The SearchResultItem type is a simple POCO. I want to set the value of the field "TrustedSource" of SearchResultItem to true or false depending on the source index.

How can I understand from which index each item came?


Solution

  • Instead of getting matched documents from searchResponse.Documents you can get results from searchResponse.Hits which also contains search results metadata like Index which will help you distinguish matched document source.

    searchResponse.Hits
        .Select(x =>
            x.Index == "trusted" 
                ? x.Source with { TrustedSource = true } 
                : x.Source with { TrustedSource = false });
        
    record SearchResultItem(int Id, bool TrustedSource);