private static IEnumerable EsqlToObject()

in src/Elastic.Clients.Elasticsearch/_Shared/Client/ElasticsearchClient.Esql.cs [70:119]


	private static IEnumerable<T> EsqlToObject<T>(ElasticsearchClient client, EsqlQueryResponse response)
	{
		// TODO: Improve performance

		using var doc = JsonSerializer.Deserialize<JsonDocument>(response.Data) ?? throw new JsonException();

		if (!doc.RootElement.TryGetProperty("columns"u8, out var columns) || (columns.ValueKind is not JsonValueKind.Array))
			throw new JsonException("");

		if (!doc.RootElement.TryGetProperty("values"u8, out var values) || (values.ValueKind is not JsonValueKind.Array))
			yield break;

		var names = columns.EnumerateArray()
			.Select(x =>
			{
				if (!x.TryGetProperty("name"u8, out var prop))
				{
					throw new JsonException();
				}

				var result = prop.GetString() ?? throw new JsonException();

				return result;
			})
			.ToArray();

		var obj = new JsonObject();
		using var ms = new MemoryStream();
		using var writer = new Utf8JsonWriter(ms);

		foreach (var document in values.EnumerateArray())
		{
			obj.Clear();
			ms.SetLength(0);
			writer.Reset();

			var properties = names.Zip(document.EnumerateArray(),
				(key, value) => new KeyValuePair<string, JsonNode?>(key, JsonValue.Create(value)));
			foreach (var property in properties)
				obj.Add(property);

			obj.WriteTo(writer);
			writer.Flush();
			ms.Position = 0;

			var result = client.SourceSerializer.Deserialize<T>(ms) ?? throw new JsonException("");

			yield return result;
		}
	}