Elasticsearch .net conditional sort

if only orders contain a "shipment_date" and only sales contain a "created_date", the following should work using a scripted sort:

var response = client.Search<DataModel>(x => x
	.Index("order*,sale*")
	.AllTypes()
    .Query(q =>
		q.Term(t => t.customerID, customerID) &&
		q.DateRange(d => d
		   .Field(f => f.created_date)
		   .GreaterThanOrEquals(fromDate)
		   .LessThanOrEquals(toDate)
		   )
		)
		.From(0)
		.Size(100)
		.Sort(s => s
			.Script(ss => ss
				.Script(sd => sd
					.Inline("doc['shipment_date'] ? doc['shipment_date'].value : doc['created_date'].value")
					.Lang("painless")
				)
			)
		)
	)
);

If you need to sort like this frequently, it may make sense to index the "shipment_date" for orders and "created_date" for sales into a commonly named field e.g. "sort_date", using copy_to, then sort on this field. It would perform better than a scripted sort.

1 Like