Skip to content

[Backport 8.1] Add support for range queries (date and numeric). #7313

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Elasticsearch.sln
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
Directory.Build.props = Directory.Build.props
Directory.Build.targets = Directory.Build.targets
dotnet-tools.json = dotnet-tools.json
exclusion.dic = exclusion.dic
global.json = global.json
issue_template.md = issue_template.md
LICENSE.txt = LICENSE.txt
Expand Down
3 changes: 2 additions & 1 deletion exclusion.dic
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ json
async
inferrer
elasticsearch
asciidocs
asciidocs
yyyy
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,39 @@
// See the LICENSE file in the project root for more information.

using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text.Json;

namespace Elastic.Clients.Elasticsearch;

internal static class ThrowHelper
{
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ThrowJsonException(string? message = null) => throw new JsonException(message);

[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ThrowUnknownTaggedUnionVariantJsonException(string variantTag, Type interfaceType) =>
throw new JsonException($"Encountered an unsupported variant tag '{variantTag}' on '{SimplifiedFullName(interfaceType)}', which could not be deserialized.");

[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ThrowInvalidOperationException(string message) =>
throw new InvalidOperationException(message);

[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
#pragma warning disable IDE0057 // Use range operator
private static string SimplifiedFullName(Type type) => type.FullName.Substring(30);
#pragma warning restore IDE0057 // Use range operator

[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ThrowJsonExceptionForMissingSettings() => throw new JsonException("Unable to retrieve client settings for JsonSerializerOptions.");

[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ThrowInvalidOperationForBulkWhenNotIStreamSerializable() => throw new InvalidOperationException("Operation must implement IStreamSerializable.");
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ internal static class TermsAggregateSerializationHelper
private static readonly byte[] s_key = Encoding.UTF8.GetBytes("key");
private static readonly byte s_period = (byte)'.';

public static bool TryDeserialiseTermsAggregate(string aggregateName, ref Utf8JsonReader reader, JsonSerializerOptions options, out IAggregate? aggregate)
public static bool TryDeserializeTermsAggregate(string aggregateName, ref Utf8JsonReader reader, JsonSerializerOptions options, out IAggregate? aggregate)
{
aggregate = null;

// We take a copy here so we can read forward to establish the term key type before we resume with final deserialisation.
// We take a copy here so we can read forward to establish the term key type before we resume with final deserialization.
var readerCopy = reader;

if (JsonHelper.TryReadUntilStringPropertyValue(ref readerCopy, s_buckets))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public static void ReadAggregate(ref Utf8JsonReader reader, JsonSerializerOption
case "lterms":
case "dterms":
{
if (TermsAggregateSerializationHelper.TryDeserialiseTermsAggregate(aggregateName, ref reader, options, out var agg))
if (TermsAggregateSerializationHelper.TryDeserializeTermsAggregate(aggregateName, ref reader, options, out var agg))
{
dictionary.Add(nameParts[1], agg);
}
Expand Down
238 changes: 238 additions & 0 deletions src/Elastic.Clients.Elasticsearch/Types/QueryDsl/RangeQuery.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.

using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Text.Json.Serialization;
using Elastic.Clients.Elasticsearch.Fluent;

namespace Elastic.Clients.Elasticsearch.QueryDsl;

public partial class Query
{
public bool TryGet<T>([NotNullWhen(true)]out T? query)
{
query = default(T);

if (Variant is T variant)
{
query = variant;
return true;
}

return false;
}
}

[JsonConverter(typeof(RangeQueryConverter))]
public class RangeQuery : SearchQuery
{
internal RangeQuery() { }
}

internal sealed class RangeQueryConverter : JsonConverter<RangeQuery>
{
public override RangeQuery? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var readerCopy = reader;

if (readerCopy.TokenType != JsonTokenType.StartObject)
ThrowHelper.ThrowJsonException($"Unexpected JSON detected. Expected {JsonTokenType.StartObject} but read {readerCopy.TokenType}.");

readerCopy.Read(); // Read past the opening token
readerCopy.Read(); // Read past the field name

using var jsonDoc = JsonDocument.ParseValue(ref readerCopy);

if (jsonDoc is null)
return null;

// When either of these properties are present, we know we have a date range query
if (jsonDoc.RootElement.TryGetProperty("format", out _) || jsonDoc.RootElement.TryGetProperty("time_zone", out _))
{
return JsonSerializer.Deserialize<DateRangeQuery>(ref reader, options);
}

JsonElement? rangeElement = null;

if (jsonDoc.RootElement.TryGetProperty("gte", out var gte))
{
rangeElement = gte;
}
else if (jsonDoc.RootElement.TryGetProperty("gt", out var gt))
{
rangeElement = gt;
}
else if(jsonDoc.RootElement.TryGetProperty("lte", out var lte))
{
rangeElement = lte;
}
else if(jsonDoc.RootElement.TryGetProperty("lt", out var lt))
{
rangeElement = lt;
}

if (!rangeElement.HasValue)
{
ThrowHelper.ThrowJsonException("Unable to determine type of range query.");
}

switch (rangeElement.Value.ValueKind)
{
case JsonValueKind.String:
return JsonSerializer.Deserialize<DateRangeQuery>(ref reader, options);
case JsonValueKind.Number:
return JsonSerializer.Deserialize<NumberRangeQuery>(ref reader, options);
}

ThrowHelper.ThrowJsonException("Unable to deserialize range query.");

// We never reach here. I wish the flow analysis could infer that this isn't needed with the help of the DoesNotReturn attributes.
return null;
}

public override void Write(Utf8JsonWriter writer, RangeQuery value, JsonSerializerOptions options) =>
JsonSerializer.Serialize(writer, value, value.GetType(), options);
}


public sealed class RangeQueryDescriptor<TDocument> : SerializableDescriptor<RangeQueryDescriptor<TDocument>>
{
private NumberRangeQueryDescriptor<TDocument> _numberRangeQueryDescriptor;
private DateRangeQueryDescriptor<TDocument> _dateRangeQueryDescriptor;

private Action<NumberRangeQueryDescriptor<TDocument>> _numberRangeQueryDescriptorAction;
private Action<DateRangeQueryDescriptor<TDocument>> _dateRangeQueryDescriptorAction;

public RangeQueryDescriptor<TDocument> DateRange(Action<DateRangeQueryDescriptor<TDocument>> configure)
{
_dateRangeQueryDescriptor = null;
_dateRangeQueryDescriptorAction = configure;
_numberRangeQueryDescriptor = null;
_numberRangeQueryDescriptorAction = null;

return Self;
}

public RangeQueryDescriptor<TDocument> NumberRange(Action<NumberRangeQueryDescriptor<TDocument>> configure)
{
_dateRangeQueryDescriptor = null;
_dateRangeQueryDescriptorAction = null;
_numberRangeQueryDescriptor = null;
_numberRangeQueryDescriptorAction = configure;

return Self;
}

public RangeQueryDescriptor<TDocument> DateRange(DateRangeQueryDescriptor<TDocument> descriptor)
{
_dateRangeQueryDescriptor = descriptor;
_dateRangeQueryDescriptorAction = null;
_numberRangeQueryDescriptor = null;
_numberRangeQueryDescriptorAction = null;

return Self;
}

public RangeQueryDescriptor<TDocument> NumberRange(NumberRangeQueryDescriptor<TDocument> descriptor)
{
_dateRangeQueryDescriptor = null;
_dateRangeQueryDescriptorAction = null;
_numberRangeQueryDescriptor = descriptor;
_numberRangeQueryDescriptorAction = null;

return Self;
}

protected override void Serialize(Utf8JsonWriter writer, JsonSerializerOptions options, IElasticsearchClientSettings settings)
{
if (_dateRangeQueryDescriptor is not null)
{
JsonSerializer.Serialize(writer, _dateRangeQueryDescriptor, options);
}
else if (_dateRangeQueryDescriptorAction is not null)
{
JsonSerializer.Serialize(writer, new DateRangeQueryDescriptor<TDocument>(_dateRangeQueryDescriptorAction), options);
}
else if (_numberRangeQueryDescriptor is not null)
{
JsonSerializer.Serialize(writer, _numberRangeQueryDescriptor, options);
}
else if (_numberRangeQueryDescriptorAction is not null)
{
JsonSerializer.Serialize(writer, new NumberRangeQueryDescriptor<TDocument>(_numberRangeQueryDescriptorAction), options);
}
}
}

public sealed class RangeQueryDescriptor : SerializableDescriptor<RangeQueryDescriptor>
{
private NumberRangeQueryDescriptor _numberRangeQueryDescriptor;
private DateRangeQueryDescriptor _dateRangeQueryDescriptor;

private Action<NumberRangeQueryDescriptor> _numberRangeQueryDescriptorAction;
private Action<DateRangeQueryDescriptor> _dateRangeQueryDescriptorAction;

public RangeQueryDescriptor DateRange(Action<DateRangeQueryDescriptor> configure)
{
_dateRangeQueryDescriptor = null;
_dateRangeQueryDescriptorAction = configure;
_numberRangeQueryDescriptor = null;
_numberRangeQueryDescriptorAction = null;

return Self;
}

public RangeQueryDescriptor NumberRange(Action<NumberRangeQueryDescriptor> configure)
{
_dateRangeQueryDescriptor = null;
_dateRangeQueryDescriptorAction = null;
_numberRangeQueryDescriptor = null;
_numberRangeQueryDescriptorAction = configure;

return Self;
}

public RangeQueryDescriptor DateRange(DateRangeQueryDescriptor descriptor)
{
_dateRangeQueryDescriptor = descriptor;
_dateRangeQueryDescriptorAction = null;
_numberRangeQueryDescriptor = null;
_numberRangeQueryDescriptorAction = null;

return Self;
}

public RangeQueryDescriptor NumberRange(NumberRangeQueryDescriptor descriptor)
{
_dateRangeQueryDescriptor = null;
_dateRangeQueryDescriptorAction = null;
_numberRangeQueryDescriptor = descriptor;
_numberRangeQueryDescriptorAction = null;

return Self;
}

protected override void Serialize(Utf8JsonWriter writer, JsonSerializerOptions options, IElasticsearchClientSettings settings)
{
if (_dateRangeQueryDescriptor is not null)
{
JsonSerializer.Serialize(writer, _dateRangeQueryDescriptor, options);
}
else if (_dateRangeQueryDescriptorAction is not null)
{
JsonSerializer.Serialize(writer, new DateRangeQueryDescriptor(_dateRangeQueryDescriptorAction), options);
}
else if (_numberRangeQueryDescriptor is not null)
{
JsonSerializer.Serialize(writer, _numberRangeQueryDescriptor, options);
}
else if (_numberRangeQueryDescriptorAction is not null)
{
JsonSerializer.Serialize(writer, new NumberRangeQueryDescriptor(_numberRangeQueryDescriptorAction), options);
}
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,55 @@ public override void Write(Utf8JsonWriter writer, Operator value, JsonSerializer
}
}

[JsonConverter(typeof(RangeRelationConverter))]
public enum RangeRelation
{
[EnumMember(Value = "within")]
Within,
[EnumMember(Value = "intersects")]
Intersects,
[EnumMember(Value = "contains")]
Contains
}

internal sealed class RangeRelationConverter : JsonConverter<RangeRelation>
{
public override RangeRelation Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var enumString = reader.GetString();
switch (enumString)
{
case "within":
return RangeRelation.Within;
case "intersects":
return RangeRelation.Intersects;
case "contains":
return RangeRelation.Contains;
}

ThrowHelper.ThrowJsonException();
return default;
}

public override void Write(Utf8JsonWriter writer, RangeRelation value, JsonSerializerOptions options)
{
switch (value)
{
case RangeRelation.Within:
writer.WriteStringValue("within");
return;
case RangeRelation.Intersects:
writer.WriteStringValue("intersects");
return;
case RangeRelation.Contains:
writer.WriteStringValue("contains");
return;
}

writer.WriteNullValue();
}
}

[JsonConverter(typeof(TextQueryTypeConverter))]
public enum TextQueryType
{
Expand Down
Loading