Search code examples
c#elasticsearchnestelasticsearch-net

NEST filtering source and creating instances of object using object constructor


I'm having an issue with source filtering in NEST client.

This is my code sample:

var searchRequest = client.Search<Report>(analysisDescriptor
  .Source(s => s
    .Includes(i => i
      .Fields(
        f => f.ReportId,
        f => f.Abstract,
        f => f.Title
      )
    )
  )
  .Size(10));

Where analysisDescriptor is new SearchDescriptor<Report>() with business logic for text search.

This is my class with constructor:

public class Report
{
  public Report(int reportId, string itemAbstract, string title)
  {
    Abstract = itemAbstract;
    ReportId = reportId;
    Title = title;
    /* Other fields */
  }

  public int ReportId { get; }
  public string Abstract { get; }
  public string Title { get; }
  /* Other fields */
}

Now the issue is that tech leads don't want to have set properties and want to have a constructor instead.

The code above almost works:

  1. ReportId is assigned
  2. Title is assigned

The issue is that Abstract field is not assigned because constructor has it declared as itemAbstract. This has been done because abstract is a reserved keyword in C#. If I change field name in constructor to @abstract - this works, but doesn't seem right because I have to use reserved keyword.

Changing Abstract to ItemAbstract doesn't seem like an option because we have it like that in database and that would require even more changes.

So ideally I'm looking for a way to pass Abstract field from my searchRequest into Report constructor as itemAbstract. Hopefully that makes sense.

I'm open to any other solution that is clean and makes sense.


Solution

  • This should work since NEST just uses Json.net for serialization.

    public Report(int reportId,[JsonProperty("abstract")]string itemAbstract, string title)
      {
        Abstract = itemAbstract;
        ReportId = reportId;
        Title = title;
        /* Other fields */
      }