-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Reintroduce suggestion feature #7894
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
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
79 changes: 79 additions & 0 deletions
79
src/Elastic.Clients.Elasticsearch/Serialization/GenericConverterAttribute.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
// 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.Reflection; | ||
using System.Text.Json.Serialization; | ||
|
||
namespace Elastic.Clients.Elasticsearch.Serialization; | ||
|
||
/// <summary> | ||
/// A custom <see cref="JsonConverterAttribute"/> used to dynamically create <see cref="JsonConverter"/> | ||
/// instances for generic classes and properties whose type arguments are unknown at compile time. | ||
/// </summary> | ||
internal class GenericConverterAttribute : | ||
JsonConverterAttribute | ||
{ | ||
private readonly int _parameterCount; | ||
|
||
/// <summary> | ||
/// The constructor. | ||
/// </summary> | ||
/// <param name="genericConverterType">The open generic type of the JSON converter class.</param> | ||
/// <param name="unwrap"> | ||
/// Set <c>true</c> to unwrap the generic type arguments of the source/target type before using them to create | ||
/// the converter instance. | ||
/// <para> | ||
/// This is especially useful, if the base converter is e.g. defined as <c>MyBaseConverter{SomeType{T}}</c> | ||
/// but the annotated property already has the concrete type <c>SomeType{T}</c>. Unwrapping the generic | ||
/// arguments will make sure to not incorrectly instantiate a converter class of type | ||
/// <c>MyBaseConverter{SomeType{SomeType{T}}}</c>. | ||
/// </para> | ||
/// </param> | ||
/// <exception cref="ArgumentException">If <paramref name="genericConverterType"/> is not a compatible generic type definition.</exception> | ||
public GenericConverterAttribute(Type genericConverterType, bool unwrap = false) | ||
{ | ||
if (!genericConverterType.IsGenericTypeDefinition) | ||
{ | ||
throw new ArgumentException( | ||
$"The generic JSON converter type '{genericConverterType.Name}' is not a generic type definition.", | ||
nameof(genericConverterType)); | ||
} | ||
|
||
GenericConverterType = genericConverterType; | ||
Unwrap = unwrap; | ||
|
||
_parameterCount = GenericConverterType.GetTypeInfo().GenericTypeParameters.Length; | ||
|
||
if (!unwrap && (_parameterCount != 1)) | ||
{ | ||
throw new ArgumentException( | ||
$"The generic JSON converter type '{genericConverterType.Name}' must accept exactly 1 generic type " + | ||
$"argument", | ||
nameof(genericConverterType)); | ||
} | ||
} | ||
|
||
public Type GenericConverterType { get; } | ||
|
||
public bool Unwrap { get; } | ||
|
||
/// <inheritdoc cref="JsonConverterAttribute.CreateConverter"/> | ||
public override JsonConverter? CreateConverter(Type typeToConvert) | ||
{ | ||
if (!Unwrap) | ||
return (JsonConverter)Activator.CreateInstance(GenericConverterType.MakeGenericType(typeToConvert)); | ||
|
||
var arguments = typeToConvert.GetGenericArguments(); | ||
if (arguments.Length != _parameterCount) | ||
{ | ||
throw new ArgumentException( | ||
$"The generic JSON converter type '{GenericConverterType.Name}' is not compatible with the target " + | ||
$"type '{typeToConvert.Name}'.", | ||
nameof(typeToConvert)); | ||
} | ||
|
||
return (JsonConverter)Activator.CreateInstance(GenericConverterType.MakeGenericType(arguments)); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
215 changes: 215 additions & 0 deletions
215
src/Elastic.Clients.Elasticsearch/Types/Core/Search/SuggestDictionary.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,215 @@ | ||
// 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.Collections.Generic; | ||
using System.Linq; | ||
using System.Text.Json; | ||
using System.Text.Json.Serialization; | ||
|
||
using Elastic.Clients.Elasticsearch.Serialization; | ||
|
||
namespace Elastic.Clients.Elasticsearch.Core.Search; | ||
|
||
[GenericConverter(typeof(SuggestDictionaryConverter<>), unwrap:true)] | ||
public sealed partial class SuggestDictionary<TDocument> : | ||
IsAReadOnlyDictionary<string, IReadOnlyCollection<ISuggest>> | ||
{ | ||
internal SuggestDictionary(IReadOnlyDictionary<string, IReadOnlyCollection<ISuggest>> backingDictionary) : | ||
base(backingDictionary) | ||
{ | ||
} | ||
|
||
public IReadOnlyCollection<TermSuggest>? GetTerm(string key) => TryGet<TermSuggest>(key); | ||
|
||
public IReadOnlyCollection<PhraseSuggest>? GetPhrase(string key) => TryGet<PhraseSuggest>(key); | ||
|
||
public IReadOnlyCollection<CompletionSuggest<TDocument>>? GetCompletion(string key) => TryGet<CompletionSuggest<TDocument>>(key); | ||
|
||
private IReadOnlyCollection<TSuggest>? TryGet<TSuggest>(string key) where TSuggest : class, ISuggest => | ||
BackingDictionary.TryGetValue(key, out var items) ? items.Cast<TSuggest>().ToArray() : null; | ||
} | ||
|
||
internal sealed class SuggestDictionaryConverter<TDocument> : | ||
JsonConverter<SuggestDictionary<TDocument>> | ||
{ | ||
public override SuggestDictionary<TDocument>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | ||
{ | ||
var dictionary = new Dictionary<string, IReadOnlyCollection<ISuggest>>(); | ||
|
||
if (reader.TokenType != JsonTokenType.StartObject) | ||
return new SuggestDictionary<TDocument>(dictionary); | ||
|
||
while (reader.Read()) | ||
{ | ||
if (reader.TokenType == JsonTokenType.EndObject) | ||
break; | ||
|
||
// TODO: Future optimization, get raw bytes span and parse based on those | ||
var name = reader.GetString() ?? throw new JsonException("Key must not be 'null'."); | ||
|
||
reader.Read(); | ||
ReadVariant(ref reader, options, dictionary, name); | ||
} | ||
|
||
return new SuggestDictionary<TDocument>(dictionary); | ||
} | ||
|
||
public static void ReadVariant(ref Utf8JsonReader reader, JsonSerializerOptions options, Dictionary<string, IReadOnlyCollection<ISuggest>> dictionary, string name) | ||
{ | ||
var nameParts = name.Split('#'); | ||
|
||
if (nameParts.Length != 2) | ||
throw new JsonException($"Unable to parse typed-key from suggestion name '{name}'"); | ||
|
||
var variantName = nameParts[0]; | ||
switch (variantName) | ||
{ | ||
case "term": | ||
{ | ||
var suggest = JsonSerializer.Deserialize<TermSuggest[]>(ref reader, options); | ||
dictionary.Add(nameParts[1], suggest); | ||
break; | ||
} | ||
|
||
case "phrase": | ||
{ | ||
var suggest = JsonSerializer.Deserialize<PhraseSuggest[]>(ref reader, options); | ||
dictionary.Add(nameParts[1], suggest); | ||
break; | ||
} | ||
|
||
case "completion": | ||
{ | ||
var suggest = JsonSerializer.Deserialize<CompletionSuggest<TDocument>[]>(ref reader, options); | ||
dictionary.Add(nameParts[1], suggest); | ||
break; | ||
} | ||
|
||
default: | ||
throw new Exception($"The suggest variant '{variantName}' in this response is currently not supported."); | ||
} | ||
} | ||
|
||
public override void Write(Utf8JsonWriter writer, SuggestDictionary<TDocument> value, JsonSerializerOptions options) => throw new NotImplementedException(); | ||
} | ||
|
||
public interface ISuggest | ||
{ | ||
} | ||
|
||
public sealed partial class TermSuggest : | ||
ISuggest | ||
{ | ||
[JsonInclude, JsonPropertyName("length")] | ||
public int Length { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("offset")] | ||
public int Offset { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("options"), SingleOrManyCollectionConverter(typeof(TermSuggestOption))] | ||
public IReadOnlyCollection<TermSuggestOption> Options { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("text")] | ||
public string Text { get; init; } | ||
} | ||
|
||
public sealed partial class TermSuggestOption | ||
{ | ||
[JsonInclude, JsonPropertyName("collate_match")] | ||
public bool? CollateMatch { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("freq")] | ||
public long Freq { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("highlighted")] | ||
public string? Highlighted { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("score")] | ||
public double Score { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("text")] | ||
public string Text { get; init; } | ||
} | ||
|
||
public sealed partial class PhraseSuggest : | ||
ISuggest | ||
{ | ||
[JsonInclude, JsonPropertyName("length")] | ||
public int Length { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("offset")] | ||
public int Offset { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("options"), SingleOrManyCollectionConverter(typeof(PhraseSuggestOption))] | ||
public IReadOnlyCollection<PhraseSuggestOption> Options { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("text")] | ||
public string Text { get; init; } | ||
} | ||
|
||
public sealed partial class PhraseSuggestOption | ||
{ | ||
[JsonInclude, JsonPropertyName("collate_match")] | ||
public bool? CollateMatch { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("highlighted")] | ||
public string? Highlighted { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("score")] | ||
public double Score { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("text")] | ||
public string Text { get; init; } | ||
} | ||
|
||
public sealed partial class CompletionSuggest<TDocument> : | ||
ISuggest | ||
{ | ||
[JsonInclude, JsonPropertyName("length")] | ||
public int Length { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("offset")] | ||
public int Offset { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("options"), GenericConverter(typeof(SingleOrManyCollectionConverter<>), unwrap:true)] | ||
public IReadOnlyCollection<CompletionSuggestOption<TDocument>> Options { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("text")] | ||
public string Text { get; init; } | ||
} | ||
|
||
public sealed partial class CompletionSuggestOption<TDocument> | ||
{ | ||
[JsonInclude, JsonPropertyName("_id")] | ||
public string? Id { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("_index")] | ||
public string? Index { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("_routing")] | ||
public string? Routing { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("_score")] | ||
public double? Score0 { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("_source")] | ||
[SourceConverter] | ||
public TDocument? Source { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("collate_match")] | ||
public bool? CollateMatch { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("contexts")] | ||
public IReadOnlyDictionary<string, IReadOnlyCollection<Context>>? Contexts { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("fields")] | ||
public IReadOnlyDictionary<string, object>? Fields { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("score")] | ||
public double? Score { get; init; } | ||
|
||
[JsonInclude, JsonPropertyName("text")] | ||
public string Text { get; init; } | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.