diff --git a/modules/library/src/it/scala/zio/elasticsearch/HttpExecutorSpec.scala b/modules/library/src/it/scala/zio/elasticsearch/HttpExecutorSpec.scala index f7a3e697d..ce84f5dea 100644 --- a/modules/library/src/it/scala/zio/elasticsearch/HttpExecutorSpec.scala +++ b/modules/library/src/it/scala/zio/elasticsearch/HttpExecutorSpec.scala @@ -1514,7 +1514,7 @@ object HttpExecutorSpec extends IntegrationSpec { doc3 <- Executor.execute(ElasticRequest.getById(index, thirdDocumentId)).documentAs[TestDocument] } yield assert(res.items.size)(equalTo(7)) && assert(res.items.map(_.error.isDefined))( - equalTo(List(false, false, false, false, false, false, true)) + equalTo(Chunk(false, false, false, false, false, false, true)) ) && assert(res.items(6).status)(equalTo(Some(404))) && assert(res.items(6).error.map(_.`type`))(equalTo(Some("document_missing_exception"))) && diff --git a/modules/library/src/main/scala/zio/elasticsearch/ElasticAggregation.scala b/modules/library/src/main/scala/zio/elasticsearch/ElasticAggregation.scala index 30bcef48a..557d72870 100644 --- a/modules/library/src/main/scala/zio/elasticsearch/ElasticAggregation.scala +++ b/modules/library/src/main/scala/zio/elasticsearch/ElasticAggregation.scala @@ -58,7 +58,7 @@ object ElasticAggregation { * an instance of empty [[zio.elasticsearch.aggregation.MultipleAggregations]]. */ final def multipleAggregations: MultipleAggregations = - Multiple(aggregations = Nil) + Multiple(aggregations = Chunk.empty) /** * Constructs a type-safe instance of [[zio.elasticsearch.aggregation.TermsAggregation]] using the specified @@ -73,7 +73,7 @@ object ElasticAggregation { * performed. */ final def termsAggregation(name: String, field: Field[_, String]): TermsAggregation = - Terms(name = name, field = field.toString, order = Chunk.empty, subAggregations = Nil, size = None) + Terms(name = name, field = field.toString, order = Chunk.empty, subAggregations = Chunk.empty, size = None) /** * Constructs an instance of [[zio.elasticsearch.aggregation.TermsAggregation]] using the specified parameters. @@ -87,7 +87,7 @@ object ElasticAggregation { * performed. */ final def termsAggregation(name: String, field: String): TermsAggregation = - Terms(name = name, field = field, order = Chunk.empty, subAggregations = Nil, size = None) + Terms(name = name, field = field, order = Chunk.empty, subAggregations = Chunk.empty, size = None) /** * Constructs a type-safe instance of [[zio.elasticsearch.aggregation.MaxAggregation]] using the specified parameters. diff --git a/modules/library/src/main/scala/zio/elasticsearch/ElasticQuery.scala b/modules/library/src/main/scala/zio/elasticsearch/ElasticQuery.scala index 2640072c4..829aa5091 100644 --- a/modules/library/src/main/scala/zio/elasticsearch/ElasticQuery.scala +++ b/modules/library/src/main/scala/zio/elasticsearch/ElasticQuery.scala @@ -16,6 +16,7 @@ package zio.elasticsearch +import zio.Chunk import zio.elasticsearch.ElasticPrimitive.ElasticPrimitive import zio.elasticsearch.query._ import zio.schema.Schema @@ -93,7 +94,14 @@ object ElasticQuery { * satisfy the criteria. */ final def filter[S: Schema](queries: ElasticQuery[S]*): BoolQuery[S] = - Bool[S](filter = queries.toList, must = Nil, mustNot = Nil, should = Nil, boost = None, minimumShouldMatch = None) + Bool[S]( + filter = Chunk.fromIterable(queries), + must = Chunk.empty, + mustNot = Chunk.empty, + should = Chunk.empty, + boost = None, + minimumShouldMatch = None + ) /** * Constructs an instance of [[zio.elasticsearch.query.BoolQuery]] with queries that must satisfy the criteria using @@ -106,7 +114,14 @@ object ElasticQuery { * satisfy the criteria. */ final def filter(queries: ElasticQuery[Any]*): BoolQuery[Any] = - Bool[Any](filter = queries.toList, must = Nil, mustNot = Nil, should = Nil, boost = None, minimumShouldMatch = None) + Bool[Any]( + filter = Chunk.fromIterable(queries), + must = Chunk.empty, + mustNot = Chunk.empty, + should = Chunk.empty, + boost = None, + minimumShouldMatch = None + ) /** * Constructs a type-safe instance of [[zio.elasticsearch.query.GeoDistanceQuery]] using the specified parameters. @@ -365,7 +380,14 @@ object ElasticQuery { * satisfy the criteria. */ final def must[S: Schema](queries: ElasticQuery[S]*): BoolQuery[S] = - Bool[S](filter = Nil, must = queries.toList, mustNot = Nil, should = Nil, boost = None, minimumShouldMatch = None) + Bool[S]( + filter = Chunk.empty, + must = Chunk.fromIterable(queries), + mustNot = Chunk.empty, + should = Chunk.empty, + boost = None, + minimumShouldMatch = None + ) /** * Constructs an instance of [[zio.elasticsearch.query.BoolQuery]] with queries that must satisfy the criteria using @@ -378,7 +400,14 @@ object ElasticQuery { * satisfy the criteria. */ final def must(queries: ElasticQuery[Any]*): BoolQuery[Any] = - Bool[Any](filter = Nil, must = queries.toList, mustNot = Nil, should = Nil, boost = None, minimumShouldMatch = None) + Bool[Any]( + filter = Chunk.empty, + must = Chunk.fromIterable(queries), + mustNot = Chunk.empty, + should = Chunk.empty, + boost = None, + minimumShouldMatch = None + ) /** * Constructs an instance of [[zio.elasticsearch.query.BoolQuery]] with queries that must not satisfy the criteria @@ -393,7 +422,14 @@ object ElasticQuery { * satisfy the criteria. */ final def mustNot[S: Schema](queries: ElasticQuery[S]*): BoolQuery[S] = - Bool[S](filter = Nil, must = Nil, mustNot = queries.toList, should = Nil, boost = None, minimumShouldMatch = None) + Bool[S]( + filter = Chunk.empty, + must = Chunk.empty, + mustNot = Chunk.fromIterable(queries), + should = Chunk.empty, + boost = None, + minimumShouldMatch = None + ) /** * Constructs an instance of [[zio.elasticsearch.query.BoolQuery]] with queries that must not satisfy the criteria @@ -406,7 +442,14 @@ object ElasticQuery { * satisfy the criteria. */ final def mustNot(queries: ElasticQuery[Any]*): BoolQuery[Any] = - Bool[Any](filter = Nil, must = Nil, mustNot = queries.toList, should = Nil, boost = None, minimumShouldMatch = None) + Bool[Any]( + filter = Chunk.empty, + must = Chunk.empty, + mustNot = Chunk.fromIterable(queries), + should = Chunk.empty, + boost = None, + minimumShouldMatch = None + ) /** * Constructs a type-safe instance of [[zio.elasticsearch.query.NestedQuery]] using the specified parameters. @@ -479,7 +522,14 @@ object ElasticQuery { * satisfy the criteria. */ final def should[S: Schema](queries: ElasticQuery[S]*): BoolQuery[S] = - Bool[S](filter = Nil, must = Nil, mustNot = Nil, should = queries.toList, boost = None, minimumShouldMatch = None) + Bool[S]( + filter = Chunk.empty, + must = Chunk.empty, + mustNot = Chunk.empty, + should = Chunk.fromIterable(queries), + boost = None, + minimumShouldMatch = None + ) /** * Constructs an instance of [[zio.elasticsearch.query.BoolQuery]] with queries that should satisfy the criteria using @@ -492,7 +542,14 @@ object ElasticQuery { * satisfy the criteria. */ final def should(queries: ElasticQuery[Any]*): BoolQuery[Any] = - Bool[Any](filter = Nil, must = Nil, mustNot = Nil, should = queries.toList, boost = None, minimumShouldMatch = None) + Bool[Any]( + filter = Chunk.empty, + must = Chunk.empty, + mustNot = Chunk.empty, + should = Chunk.fromIterable(queries), + boost = None, + minimumShouldMatch = None + ) /** * Constructs a type-safe instance of [[zio.elasticsearch.query.WildcardQuery]] using the specified parameters. @@ -574,7 +631,7 @@ object ElasticQuery { * an instance of [[zio.elasticsearch.query.TermsQuery]] that represents the term query to be performed. */ final def terms[S](field: Field[S, String], values: String*): Terms[S] = - Terms(field = field.toString, values = values.toList, boost = None) + Terms(field = field.toString, values = Chunk.fromIterable(values), boost = None) /** * Constructs an instance of [[zio.elasticsearch.query.TermsQuery]] using the specified parameters. @@ -590,7 +647,7 @@ object ElasticQuery { * an instance of [[zio.elasticsearch.query.TermsQuery]] that represents the term query to be performed. */ final def terms(field: String, values: String*): Terms[Any] = - Terms(field = field, values = values.toList, boost = None) + Terms(field = field, values = Chunk.fromIterable(values), boost = None) /** * Constructs a type-safe instance of [[zio.elasticsearch.query.WildcardQuery]] using the specified parameters. diff --git a/modules/library/src/main/scala/zio/elasticsearch/ElasticRequest.scala b/modules/library/src/main/scala/zio/elasticsearch/ElasticRequest.scala index 1f8832a8d..f5422c6f0 100644 --- a/modules/library/src/main/scala/zio/elasticsearch/ElasticRequest.scala +++ b/modules/library/src/main/scala/zio/elasticsearch/ElasticRequest.scala @@ -65,7 +65,7 @@ object ElasticRequest { * an instance of [[BulkRequest]] that represents the bulk operation to be performed. */ final def bulk(requests: BulkableRequest[_]*): BulkRequest = - Bulk.of(requests = requests: _*) + Bulk(requests = Chunk.fromIterable(requests), index = None, refresh = None, routing = None) /** * Constructs an instance of [[CountRequest]] for whole specified index. @@ -368,7 +368,7 @@ object ElasticRequest { with HasRouting[BulkRequest] private[elasticsearch] final case class Bulk( - requests: List[BulkableRequest[_]], + requests: Chunk[BulkableRequest[_]], index: Option[IndexName], refresh: Option[Boolean], routing: Option[Routing] @@ -382,38 +382,33 @@ object ElasticRequest { lazy val body: String = requests.flatMap { r => (r: @unchecked) match { case Create(index, document, _, routing) => - List(getActionAndMeta("create", List(("_index", Some(index)), ("routing", routing))), document.json) + Chunk(getActionAndMeta("create", Chunk(("_index", Some(index)), ("routing", routing))), document.json) case CreateWithId(index, id, document, _, routing) => - List( - getActionAndMeta("create", List(("_index", Some(index)), ("_id", Some(id)), ("routing", routing))), + Chunk( + getActionAndMeta("create", Chunk(("_index", Some(index)), ("_id", Some(id)), ("routing", routing))), document.json ) case CreateOrUpdate(index, id, document, _, routing) => - List( - getActionAndMeta("index", List(("_index", Some(index)), ("_id", Some(id)), ("routing", routing))), + Chunk( + getActionAndMeta("index", Chunk(("_index", Some(index)), ("_id", Some(id)), ("routing", routing))), document.json ) case DeleteById(index, id, _, routing) => - List(getActionAndMeta("delete", List(("_index", Some(index)), ("_id", Some(id)), ("routing", routing)))) + Chunk(getActionAndMeta("delete", Chunk(("_index", Some(index)), ("_id", Some(id)), ("routing", routing)))) case Update(index, id, Some(document), _, routing, None, _) => - List( - getActionAndMeta("update", List(("_index", Some(index)), ("_id", Some(id)), ("routing", routing))), + Chunk( + getActionAndMeta("update", Chunk(("_index", Some(index)), ("_id", Some(id)), ("routing", routing))), Obj("doc" -> document.json) ) case Update(index, id, None, _, routing, Some(script), _) => - List( - getActionAndMeta("update", List(("_index", Some(index)), ("_id", Some(id)), ("routing", routing))), + Chunk( + getActionAndMeta("update", Chunk(("_index", Some(index)), ("_id", Some(id)), ("routing", routing))), Obj("script" -> script.toJson) ) } }.mkString(start = "", sep = "\n", end = "\n") } - object Bulk { - def of(requests: BulkableRequest[_]*): Bulk = - Bulk(requests = requests.toList, index = None, refresh = None, routing = None) - } - sealed trait CountRequest extends ElasticRequest[Int] with HasRouting[CountRequest] private[elasticsearch] final case class Count( @@ -625,7 +620,7 @@ object ElasticRequest { self.copy(size = Some(value)) def sort(sort: Sort, sorts: Sort*): SearchRequest = - self.copy(sortBy = sortBy ++ (sort :: sorts.toList)) + self.copy(sortBy = sortBy ++ (sort +: sorts)) def toJson: Json = { val fromJson: Json = self.from.fold(Obj())(f => Obj("from" -> f.toJson)) @@ -637,15 +632,15 @@ object ElasticRequest { val searchAfterJson: Json = searchAfter.fold(Obj())(sa => Obj("search_after" -> sa)) val sortJson: Json = - if (self.sortBy.nonEmpty) Obj("sort" -> Arr(self.sortBy.map(_.paramsToJson): _*)) else Obj() + if (self.sortBy.nonEmpty) Obj("sort" -> Arr(self.sortBy.map(_.paramsToJson))) else Obj() val sourceJson: Json = (included, excluded) match { case (None, None) => Obj() case (included, excluded) => Obj("_source" -> { - val includes = included.fold(Obj())(included => Obj("includes" -> Arr(included.map(_.toJson): _*))) - val excludes = excluded.fold(Obj())(excluded => Obj("excludes" -> Arr(excluded.map(_.toJson): _*))) + val includes = included.fold(Obj())(included => Obj("includes" -> Arr(included.map(_.toJson)))) + val excludes = excluded.fold(Obj())(excluded => Obj("excludes" -> Arr(excluded.map(_.toJson)))) includes merge excludes }) } @@ -706,7 +701,7 @@ object ElasticRequest { self.copy(searchAfter = Some(value)) def sort(sort: Sort, sorts: Sort*): SearchAndAggregateRequest = - self.copy(sortBy = sortBy ++ (sort :: sorts.toList)) + self.copy(sortBy = sortBy ++ (sort +: sorts)) def toJson: Json = { val fromJson: Json = self.from.fold(Obj())(f => Obj("from" -> f.toJson)) @@ -718,15 +713,15 @@ object ElasticRequest { val searchAfterJson: Json = searchAfter.fold(Obj())(sa => Obj("search_after" -> sa)) val sortJson: Json = - if (self.sortBy.nonEmpty) Obj("sort" -> Arr(self.sortBy.map(_.paramsToJson): _*)) else Obj() + if (self.sortBy.nonEmpty) Obj("sort" -> Arr(self.sortBy.map(_.paramsToJson))) else Obj() val sourceJson: Json = (included, excluded) match { case (None, None) => Obj() case (included, excluded) => Obj("_source" -> { - val includes = included.fold(Obj())(included => Obj("includes" -> Arr(included.map(_.toJson): _*))) - val excludes = excluded.fold(Obj())(excluded => Obj("excludes" -> Arr(excluded.map(_.toJson): _*))) + val includes = included.fold(Obj())(included => Obj("includes" -> Arr(included.map(_.toJson)))) + val excludes = excluded.fold(Obj())(excluded => Obj("excludes" -> Arr(excluded.map(_.toJson)))) includes merge excludes }) } @@ -806,7 +801,7 @@ object ElasticRequest { query.foldLeft(Obj("script" -> script.toJson))((scriptJson, q) => scriptJson merge q.toJson) } - private def getActionAndMeta(requestType: String, parameters: List[(String, Any)]): String = + private def getActionAndMeta(requestType: String, parameters: Chunk[(String, Any)]): String = parameters.collect { case (name, Some(value)) => s""""$name" : "$value"""" } .mkString(s"""{ "$requestType" : { """, ", ", " } }") } diff --git a/modules/library/src/main/scala/zio/elasticsearch/Field.scala b/modules/library/src/main/scala/zio/elasticsearch/Field.scala index 386b5ff35..dff74b343 100644 --- a/modules/library/src/main/scala/zio/elasticsearch/Field.scala +++ b/modules/library/src/main/scala/zio/elasticsearch/Field.scala @@ -16,6 +16,7 @@ package zio.elasticsearch +import zio.Chunk import zio.elasticsearch.ElasticPrimitive.ElasticPrimitive import zio.schema.{AccessorBuilder, Schema} @@ -60,12 +61,12 @@ private[elasticsearch] final case class Field[-S, +A](parent: Option[Field[S, _] override def toString: String = { @tailrec - def loop(field: Field[_, _], acc: List[String]): List[String] = field match { + def loop(field: Field[_, _], acc: Chunk[String]): Chunk[String] = field match { case Field(None, name) => s"$name" +: acc case Field(Some(parent), name) => loop(parent, s".$name" +: acc) } - loop(self, Nil).mkString + loop(self, Chunk.empty).mkString } /** diff --git a/modules/library/src/main/scala/zio/elasticsearch/aggregation/Aggregations.scala b/modules/library/src/main/scala/zio/elasticsearch/aggregation/Aggregations.scala index cd5f40735..3495b5eac 100644 --- a/modules/library/src/main/scala/zio/elasticsearch/aggregation/Aggregations.scala +++ b/modules/library/src/main/scala/zio/elasticsearch/aggregation/Aggregations.scala @@ -128,7 +128,7 @@ sealed trait MultipleAggregations extends ElasticAggregation with WithAgg { def aggregations(aggregations: SingleElasticAggregation*): MultipleAggregations } -private[elasticsearch] final case class Multiple(aggregations: List[SingleElasticAggregation]) +private[elasticsearch] final case class Multiple(aggregations: Chunk[SingleElasticAggregation]) extends MultipleAggregations { self => def aggregations(aggregations: SingleElasticAggregation*): MultipleAggregations = self.copy(aggregations = self.aggregations ++ aggregations) @@ -151,11 +151,11 @@ private[elasticsearch] final case class Terms( name: String, field: String, order: Chunk[AggregationOrder], - subAggregations: List[SingleElasticAggregation], + subAggregations: Chunk[SingleElasticAggregation], size: Option[Int] ) extends TermsAggregation { self => def orderBy(order: AggregationOrder, orders: AggregationOrder*): TermsAggregation = - self.copy(order = self.order ++ (order :: orders.toList)) + self.copy(order = self.order ++ (order +: orders)) def size(value: Int): TermsAggregation = self.copy(size = Some(value)) @@ -174,9 +174,9 @@ private[elasticsearch] final case class Terms( case o :: Nil => Obj("order" -> Obj(o.value -> o.order.toString.toJson)) case orders => - Obj("order" -> Arr(orders.collect { case AggregationOrder(value, order) => + Obj("order" -> Arr(Chunk.fromIterable(orders).collect { case AggregationOrder(value, order) => Obj(value -> order.toString.toJson) - }: _*)) + })) } val sizeJson = size.fold(Obj())(s => Obj("size" -> s.toJson)) diff --git a/modules/library/src/main/scala/zio/elasticsearch/executor/HttpExecutor.scala b/modules/library/src/main/scala/zio/elasticsearch/executor/HttpExecutor.scala index 184f47e64..c169362bf 100644 --- a/modules/library/src/main/scala/zio/elasticsearch/executor/HttpExecutor.scala +++ b/modules/library/src/main/scala/zio/elasticsearch/executor/HttpExecutor.scala @@ -131,7 +131,7 @@ private[elasticsearch] final class HttpExecutor private (esConfig: ElasticConfig val uri = (r.index match { case Some(index) => uri"${esConfig.uri}/$index/$Bulk" case None => uri"${esConfig.uri}/$Bulk" - }).withParams(getQueryParams(List(("refresh", r.refresh), ("routing", r.routing)))) + }).withParams(getQueryParams(Chunk(("refresh", r.refresh), ("routing", r.routing)))) sendRequestWithCustomResponse( baseRequest @@ -153,7 +153,7 @@ private[elasticsearch] final class HttpExecutor private (esConfig: ElasticConfig private def executeCount(r: Count): Task[Int] = { val req = baseRequest - .get(uri"${esConfig.uri}/${r.index}/$Count".withParams(getQueryParams(List(("routing", r.routing))))) + .get(uri"${esConfig.uri}/${r.index}/$Count".withParams(getQueryParams(Chunk(("routing", r.routing))))) .contentType(ApplicationJson) .response(asJson[CountResponse]) @@ -174,7 +174,7 @@ private[elasticsearch] final class HttpExecutor private (esConfig: ElasticConfig private def executeCreate(r: Create): Task[DocumentId] = { val uri = uri"${esConfig.uri}/${r.index}/$Doc" - .withParams(getQueryParams(List(("refresh", r.refresh), ("routing", r.routing)))) + .withParams(getQueryParams(Chunk(("refresh", r.refresh), ("routing", r.routing)))) sendRequestWithCustomResponse[CreateResponse]( baseRequest @@ -200,7 +200,7 @@ private[elasticsearch] final class HttpExecutor private (esConfig: ElasticConfig private def executeCreateWithId(r: CreateWithId): Task[CreationOutcome] = { val uri = uri"${esConfig.uri}/${r.index}/$Create/${r.id}" - .withParams(getQueryParams(List(("refresh", r.refresh), ("routing", r.routing)))) + .withParams(getQueryParams(Chunk(("refresh", r.refresh), ("routing", r.routing)))) sendRequest( baseRequest @@ -232,7 +232,7 @@ private[elasticsearch] final class HttpExecutor private (esConfig: ElasticConfig private def executeCreateOrUpdate(r: CreateOrUpdate): Task[Unit] = { val uri = uri"${esConfig.uri}/${r.index}/$Doc/${r.id}" - .withParams(getQueryParams(List(("refresh", r.refresh), ("routing", r.routing)))) + .withParams(getQueryParams(Chunk(("refresh", r.refresh), ("routing", r.routing)))) sendRequest(baseRequest.put(uri).contentType(ApplicationJson).body(r.document.json)).flatMap { response => response.code match { @@ -265,7 +265,7 @@ private[elasticsearch] final class HttpExecutor private (esConfig: ElasticConfig private def executeDeleteById(r: DeleteById): Task[DeletionOutcome] = { val uri = uri"${esConfig.uri}/${r.index}/$Doc/${r.id}" - .withParams(getQueryParams(List(("refresh", r.refresh), ("routing", r.routing)))) + .withParams(getQueryParams(Chunk(("refresh", r.refresh), ("routing", r.routing)))) sendRequest(baseRequest.delete(uri)).flatMap { response => response.code match { @@ -279,7 +279,7 @@ private[elasticsearch] final class HttpExecutor private (esConfig: ElasticConfig private def executeDeleteByQuery(r: DeleteByQuery): Task[DeletionOutcome] = { val uri = uri"${esConfig.uri}/${r.index}/$DeleteByQuery".withParams( - getQueryParams(List(("refresh", r.refresh), ("routing", r.routing))) + getQueryParams(Chunk(("refresh", r.refresh), ("routing", r.routing))) ) sendRequest( @@ -306,7 +306,7 @@ private[elasticsearch] final class HttpExecutor private (esConfig: ElasticConfig } private def executeExists(r: Exists): Task[Boolean] = { - val uri = uri"${esConfig.uri}/${r.index}/$Doc/${r.id}".withParams(getQueryParams(List(("routing", r.routing)))) + val uri = uri"${esConfig.uri}/${r.index}/$Doc/${r.id}".withParams(getQueryParams(Chunk(("routing", r.routing)))) sendRequest(baseRequest.head(uri)).flatMap { response => response.code match { @@ -319,7 +319,7 @@ private[elasticsearch] final class HttpExecutor private (esConfig: ElasticConfig private def executeGetById(r: GetById): Task[GetResult] = { val uri = uri"${esConfig.uri}/${r.index}/$Doc/${r.id}".withParams( - getQueryParams(List(("refresh", r.refresh), ("routing", r.routing))) + getQueryParams(Chunk(("refresh", r.refresh), ("routing", r.routing))) ) sendRequestWithCustomResponse[GetResponse]( @@ -348,7 +348,7 @@ private[elasticsearch] final class HttpExecutor private (esConfig: ElasticConfig response.body.fold( e => ZIO.fail(new ElasticException(s"Exception occurred: ${e.getMessage}")), value => - value.resultsWithHighlightsAndSort match { + value.resultsWithHighlightsAndSort.toList match { case Nil => ZIO.succeed((Chunk.empty, None)) case _ => @@ -368,7 +368,7 @@ private[elasticsearch] final class HttpExecutor private (esConfig: ElasticConfig private def executeSearch(r: Search): Task[SearchResult] = sendRequestWithCustomResponse( baseRequest - .post(uri"${esConfig.uri}/${r.index}/$Search".withParams(getQueryParams(List(("routing", r.routing))))) + .post(uri"${esConfig.uri}/${r.index}/$Search".withParams(getQueryParams(Chunk(("routing", r.routing))))) .response(asJson[SearchWithAggregationsResponse]) .contentType(ApplicationJson) .body(r.toJson) @@ -385,7 +385,7 @@ private[elasticsearch] final class HttpExecutor private (esConfig: ElasticConfig itemsFromDocumentsWithHighlightsSortAndInnerHits( value.resultsWithHighlightsAndSort, innerHitsResults - ).toList, + ), value ) } @@ -413,7 +413,7 @@ private[elasticsearch] final class HttpExecutor private (esConfig: ElasticConfig if (r.sortBy.isEmpty) { Json.Obj("sort" -> Json.Arr(Json.Str(ShardDoc))) } else { - Obj("sort" -> Arr(r.sortBy.toList.map(_.paramsToJson): _*)) + Obj("sort" -> Arr(r.sortBy.map(_.paramsToJson))) } val searchAfterJson = searchAfter.map(sa => Json.Obj("search_after" -> sa)).getOrElse(Obj()) sendRequestWithCustomResponse( @@ -428,7 +428,7 @@ private[elasticsearch] final class HttpExecutor private (esConfig: ElasticConfig response.body.fold( e => ZIO.fail(new ElasticException(s"Exception occurred: ${e.getMessage}")), body => { - body.resultsWithHighlightsAndSort match { + body.resultsWithHighlightsAndSort.toList match { case Nil => ZIO.succeed((Chunk.empty, None)) case _ => body.pitId match { @@ -469,7 +469,7 @@ private[elasticsearch] final class HttpExecutor private (esConfig: ElasticConfig baseRequest .post( uri"${esConfig.uri}/${r.index}/$Search?typed_keys" - .withParams(getQueryParams(List(("routing", r.routing)))) + .withParams(getQueryParams(Chunk(("routing", r.routing)))) .addQuerySegment(QuerySegment.Value("typed_keys")) ) .response(asJson[SearchWithAggregationsResponse]) @@ -483,7 +483,7 @@ private[elasticsearch] final class HttpExecutor private (esConfig: ElasticConfig value => ZIO.succeed( new SearchAndAggregateResult( - itemsFromDocumentsWithHighlights(value.resultsWithHighlightsAndSort).toList, + itemsFromDocumentsWithHighlights(value.resultsWithHighlightsAndSort), value.aggs, value ) @@ -499,12 +499,12 @@ private[elasticsearch] final class HttpExecutor private (esConfig: ElasticConfig baseRequest .post( uri"${esConfig.uri}/${r.index}/$Search".withParams( - getQueryParams(List((Scroll, Some(config.keepAlive)), ("routing", r.routing))) + getQueryParams(Chunk((Scroll, Some(config.keepAlive)), ("routing", r.routing))) ) ) .response(asJson[SearchWithAggregationsResponse]) .contentType(ApplicationJson) - .body(r.query.toJson merge Obj("sort" -> Arr(r.sortBy.toList.map(_.paramsToJson): _*))) + .body(r.query.toJson merge Obj("sort" -> Arr(r.sortBy.map(_.paramsToJson)))) ).flatMap { response => response.code match { case HttpOk => @@ -525,7 +525,7 @@ private[elasticsearch] final class HttpExecutor private (esConfig: ElasticConfig baseRequest .post( uri"${esConfig.uri}/${r.index}/$Update/${r.id}".withParams( - getQueryParams(List(("refresh", r.refresh), ("routing", r.routing))) + getQueryParams(Chunk(("refresh", r.refresh), ("routing", r.routing))) ) ) .contentType(ApplicationJson) @@ -543,7 +543,7 @@ private[elasticsearch] final class HttpExecutor private (esConfig: ElasticConfig baseRequest .post( uri"${esConfig.uri}/${r.index}/$UpdateByQuery".withParams( - getQueryParams(List(("conflicts", r.conflicts), ("refresh", r.refresh), ("routing", r.routing))) + getQueryParams(Chunk(("conflicts", r.conflicts), ("refresh", r.refresh), ("routing", r.routing))) ) ) .response(asJson[UpdateByQueryResponse]) @@ -566,7 +566,7 @@ private[elasticsearch] final class HttpExecutor private (esConfig: ElasticConfig } } - private def getQueryParams(parameters: List[(String, Any)]): ScalaMap[String, String] = + private def getQueryParams(parameters: Chunk[(String, Any)]): ScalaMap[String, String] = parameters.collect { case (name, Some(value)) => (name, value.toString) }.toMap private def handleFailures(response: Response[Either[String, String]]): ElasticException = @@ -591,14 +591,14 @@ private[elasticsearch] final class HttpExecutor private (esConfig: ElasticConfig ) } - private def itemsFromDocumentsWithHighlights(results: List[DocumentWithHighlightsAndSort]): Chunk[Item] = - Chunk.fromIterable(results).map(r => Item(raw = r.source, highlight = r.highlight, sort = r.sort)) + private def itemsFromDocumentsWithHighlights(results: Chunk[DocumentWithHighlightsAndSort]): Chunk[Item] = + results.map(r => Item(raw = r.source, highlight = r.highlight, sort = r.sort)) private def itemsFromDocumentsWithHighlightsSortAndInnerHits( - results: List[DocumentWithHighlightsAndSort], - innerHits: List[Map[String, List[Json]]] + results: Chunk[DocumentWithHighlightsAndSort], + innerHits: Chunk[Map[String, Chunk[Json]]] ): Chunk[Item] = - Chunk.fromIterable(results).zip(innerHits).map { case (r, innerHits) => + results.zip(innerHits).map { case (r, innerHits) => Item(raw = r.source, highlight = r.highlight, innerHits = innerHits, sort = r.sort) } diff --git a/modules/library/src/main/scala/zio/elasticsearch/executor/response/AggregationResponse.scala b/modules/library/src/main/scala/zio/elasticsearch/executor/response/AggregationResponse.scala index 2e0221dc2..a9169f333 100644 --- a/modules/library/src/main/scala/zio/elasticsearch/executor/response/AggregationResponse.scala +++ b/modules/library/src/main/scala/zio/elasticsearch/executor/response/AggregationResponse.scala @@ -16,6 +16,7 @@ package zio.elasticsearch.executor.response +import zio.Chunk import zio.json.ast.Json import zio.json.ast.Json.Obj import zio.json.{DeriveJsonDecoder, JsonDecoder, jsonField} @@ -40,7 +41,7 @@ private[elasticsearch] final case class TermsAggregationResponse( docErrorCount: Int, @jsonField("sum_other_doc_count") sumOtherDocCount: Int, - buckets: List[TermsAggregationBucket] + buckets: Chunk[TermsAggregationBucket] ) extends AggregationResponse private[elasticsearch] object TermsAggregationResponse { @@ -78,7 +79,7 @@ private[elasticsearch] object TermsAggregationBucket { docErrorCount = objFields("doc_count_error_upper_bound").unsafeAs[Int], sumOtherDocCount = objFields("sum_other_doc_count").unsafeAs[Int], buckets = objFields("buckets") - .unsafeAs[List[Json]] + .unsafeAs[Chunk[Json]] .map(_.unsafeAs[TermsAggregationBucket](TermsAggregationBucket.decoder)) ) ) diff --git a/modules/library/src/main/scala/zio/elasticsearch/executor/response/BulkResponse.scala b/modules/library/src/main/scala/zio/elasticsearch/executor/response/BulkResponse.scala index 5504d3500..a2c3bb358 100644 --- a/modules/library/src/main/scala/zio/elasticsearch/executor/response/BulkResponse.scala +++ b/modules/library/src/main/scala/zio/elasticsearch/executor/response/BulkResponse.scala @@ -16,12 +16,13 @@ package zio.elasticsearch.executor.response +import zio.Chunk import zio.json.{DeriveJsonDecoder, JsonDecoder} final case class BulkResponse private[elasticsearch] ( took: Int, errors: Boolean, - items: List[BulkResponseItem] + items: Chunk[BulkResponseItem] ) private[elasticsearch] object BulkResponse { diff --git a/modules/library/src/main/scala/zio/elasticsearch/executor/response/Hits.scala b/modules/library/src/main/scala/zio/elasticsearch/executor/response/Hits.scala index bd65232ae..34034dbfc 100644 --- a/modules/library/src/main/scala/zio/elasticsearch/executor/response/Hits.scala +++ b/modules/library/src/main/scala/zio/elasticsearch/executor/response/Hits.scala @@ -16,13 +16,14 @@ package zio.elasticsearch.executor.response +import zio.Chunk import zio.json.{DeriveJsonDecoder, JsonDecoder, jsonField} private[elasticsearch] final case class Hits( total: Total, @jsonField("max_score") maxScore: Option[Double] = None, - hits: List[Hit] + hits: Chunk[Hit] ) private[elasticsearch] object Hits { diff --git a/modules/library/src/main/scala/zio/elasticsearch/executor/response/SearchWithAggregationsResponse.scala b/modules/library/src/main/scala/zio/elasticsearch/executor/response/SearchWithAggregationsResponse.scala index f0059e114..c8ec20774 100644 --- a/modules/library/src/main/scala/zio/elasticsearch/executor/response/SearchWithAggregationsResponse.scala +++ b/modules/library/src/main/scala/zio/elasticsearch/executor/response/SearchWithAggregationsResponse.scala @@ -16,6 +16,7 @@ package zio.elasticsearch.executor.response +import zio.Chunk import zio.json.ast.Json import zio.json.ast.Json.Obj import zio.json.{DeriveJsonDecoder, JsonDecoder, jsonField} @@ -34,11 +35,11 @@ private[elasticsearch] final case class SearchWithAggregationsResponse( hits: Hits, aggregations: Option[Json] ) { - lazy val innerHitsResults: Either[String, List[Map[String, List[Json]]]] = + lazy val innerHitsResults: Either[String, Chunk[Map[String, Chunk[Json]]]] = Validation .validateAll( hits.hits - .map(_.innerHits.fold[Validation[String, Map[String, List[Json]]]](Validation.succeed(Map.empty)) { + .map(_.innerHits.fold[Validation[String, Map[String, Chunk[Json]]]](Validation.succeed(Map.empty)) { innerHits => Validation .validateAll( @@ -55,7 +56,7 @@ private[elasticsearch] final case class SearchWithAggregationsResponse( ) .toEitherWith(_.mkString(", ")) - lazy val resultsWithHighlightsAndSort: List[DocumentWithHighlightsAndSort] = + lazy val resultsWithHighlightsAndSort: Chunk[DocumentWithHighlightsAndSort] = hits.hits.map(h => DocumentWithHighlightsAndSort(h.source, h.highlight, h.sort)) lazy val lastSortField: Option[Json] = hits.hits.lastOption.flatMap(_.sort) @@ -68,7 +69,7 @@ private[elasticsearch] final case class SearchWithAggregationsResponse( case Right(res) => (Validation .validateAll( - res.fields.toList.map { case (field, data) => + res.fields.map { case (field, data) => ZValidation.fromEither( (field: @unchecked) match { case str if str.contains("max#") => diff --git a/modules/library/src/main/scala/zio/elasticsearch/highlights/Highlights.scala b/modules/library/src/main/scala/zio/elasticsearch/highlights/Highlights.scala index 5bc9df7f8..0fd6e7900 100644 --- a/modules/library/src/main/scala/zio/elasticsearch/highlights/Highlights.scala +++ b/modules/library/src/main/scala/zio/elasticsearch/highlights/Highlights.scala @@ -99,15 +99,15 @@ final case class Highlights( def withHighlight(field: String, config: HighlightConfig): Highlights = self.copy(fields = HighlightField(field, config) +: self.fields) - private[elasticsearch] def toJson: Json = Obj("highlight" -> Obj(configList: _*).merge(fieldsJson)) + private[elasticsearch] def toJson: Json = Obj("highlight" -> Obj(configChunk).merge(fieldsJson)) - private lazy val configList: List[(String, Json)] = config.toList + private lazy val configChunk: Chunk[(String, Json)] = Chunk.fromIterable(config) private lazy val fieldsJson: Json = if (explicitFieldOrder) { Obj("fields" -> Arr(fields.reverse.map(_.toJsonObj))) } else { - Obj("fields" -> Obj(fields.reverse.map(_.toStringJsonPair): _*)) + Obj("fields" -> Obj(fields.reverse.map(_.toStringJsonPair))) } } @@ -116,7 +116,7 @@ object Highlights { } private[elasticsearch] final case class HighlightField(field: String, config: HighlightConfig = Map.empty) { - def toStringJsonPair: (String, Obj) = field -> Obj(config.toList: _*) + def toStringJsonPair: (String, Obj) = field -> Obj(Chunk.fromIterable(config)) - def toJsonObj: Json = Obj(field -> Obj(config.toList: _*)) + def toJsonObj: Json = Obj(toStringJsonPair) } diff --git a/modules/library/src/main/scala/zio/elasticsearch/query/InnerHits.scala b/modules/library/src/main/scala/zio/elasticsearch/query/InnerHits.scala index 7fdff81b4..b022098f7 100644 --- a/modules/library/src/main/scala/zio/elasticsearch/query/InnerHits.scala +++ b/modules/library/src/main/scala/zio/elasticsearch/query/InnerHits.scala @@ -16,6 +16,7 @@ package zio.elasticsearch.query +import zio.Chunk import zio.json.ast.Json import zio.json.ast.Json.{Num, Obj, Str} @@ -35,7 +36,7 @@ private[elasticsearch] final case class InnerHits( def toStringJsonPair: (String, Json) = "inner_hits" -> Obj( - List(from.map("from" -> Num(_)), size.map("size" -> Num(_)), name.map("name" -> Str(_))).flatten: _* + Chunk(from.map("from" -> Num(_)), size.map("size" -> Num(_)), name.map("name" -> Str(_))).flatten ) } diff --git a/modules/library/src/main/scala/zio/elasticsearch/query/Queries.scala b/modules/library/src/main/scala/zio/elasticsearch/query/Queries.scala index 490b49bf3..7927abc5c 100644 --- a/modules/library/src/main/scala/zio/elasticsearch/query/Queries.scala +++ b/modules/library/src/main/scala/zio/elasticsearch/query/Queries.scala @@ -52,10 +52,10 @@ sealed trait BoolQuery[S] extends ElasticQuery[S] with HasBoost[BoolQuery[S]] wi } private[elasticsearch] final case class Bool[S]( - filter: List[ElasticQuery[S]], - must: List[ElasticQuery[S]], - mustNot: List[ElasticQuery[S]], - should: List[ElasticQuery[S]], + filter: Chunk[ElasticQuery[S]], + must: Chunk[ElasticQuery[S]], + mustNot: Chunk[ElasticQuery[S]], + should: Chunk[ElasticQuery[S]], boost: Option[Double], minimumShouldMatch: Option[Int] ) extends BoolQuery[S] { self => @@ -86,15 +86,15 @@ private[elasticsearch] final case class Bool[S]( def paramsToJson(fieldPath: Option[String]): Json = { val boolFields = Chunk( - if (filter.nonEmpty) Some("filter" -> Arr(filter.map(_.paramsToJson(fieldPath)): _*)) else None, - if (must.nonEmpty) Some("must" -> Arr(must.map(_.paramsToJson(fieldPath)): _*)) else None, - if (mustNot.nonEmpty) Some("must_not" -> Arr(mustNot.map(_.paramsToJson(fieldPath)): _*)) else None, - if (should.nonEmpty) Some("should" -> Arr(should.map(_.paramsToJson(fieldPath)): _*)) else None, + if (filter.nonEmpty) Some("filter" -> Arr(filter.map(_.paramsToJson(fieldPath)))) else None, + if (must.nonEmpty) Some("must" -> Arr(must.map(_.paramsToJson(fieldPath)))) else None, + if (mustNot.nonEmpty) Some("must_not" -> Arr(mustNot.map(_.paramsToJson(fieldPath)))) else None, + if (should.nonEmpty) Some("should" -> Arr(should.map(_.paramsToJson(fieldPath)))) else None, boost.map("boost" -> Num(_)), minimumShouldMatch.map("minimum_should_match" -> Num(_)) ).collect { case Some(obj) => obj } - Obj("bool" -> Obj(boolFields: _*)) + Obj("bool" -> Obj(boolFields)) } def should[S1 <: S: Schema](queries: ElasticQuery[S1]*): BoolQuery[S1] = @@ -260,7 +260,7 @@ private[elasticsearch] final case class HasChild[S]( maxChildren.map("max_children" -> Json.Num(_)), minChildren.map("min_children" -> Json.Num(_)), scoreMode.map(sm => "score_mode" -> Json.Str(sm.toString.toLowerCase)) - ).flatten: _* + ).flatten ) ) @@ -329,7 +329,7 @@ private[elasticsearch] final case class HasParent[S]( ignoreUnmapped.map("ignore_unmapped" -> Json.Bool(_)), score.map("score" -> Json.Bool(_)), innerHitsField.map(_.toStringJsonPair) - ).flatten: _* + ).flatten ) ) @@ -351,7 +351,7 @@ private[elasticsearch] final case class MatchAll(boost: Option[Double]) extends self.copy(boost = Some(value)) def paramsToJson(fieldPath: Option[String]): Json = - Obj("match_all" -> Obj(boost.map("boost" -> Num(_)).toList: _*)) + Obj("match_all" -> Obj(Chunk.fromIterable(boost.map("boost" -> Num(_))))) } sealed trait MatchPhraseQuery[S] extends ElasticQuery[S] @@ -389,7 +389,7 @@ private[elasticsearch] final case class Nested[S]( scoreMode.map(scoreMode => "score_mode" -> Str(scoreMode.toString.toLowerCase)), ignoreUnmapped.map("ignore_unmapped" -> Json.Bool(_)), innerHitsField.map(_.toStringJsonPair) - ).flatten: _* + ).flatten ) ) @@ -488,7 +488,7 @@ private[elasticsearch] final case class Range[S, A, LB <: LowerBound, UB <: Uppe upper.toJson, boost.map("boost" -> Num(_)), format.map("format" -> Str(_)) - ).flatten: _* + ).flatten ) ) ) @@ -523,7 +523,7 @@ private[elasticsearch] final case class Term[S]( val termFields = Some("value" -> value.toJson) ++ boost.map("boost" -> Num(_)) ++ caseInsensitive.map( "case_insensitive" -> Json.Bool(_) ) - Obj("term" -> Obj(fieldPath.foldRight(field)(_ + "." + _) -> Obj(termFields.toList: _*))) + Obj("term" -> Obj(fieldPath.foldRight(field)(_ + "." + _) -> Obj(Chunk.fromIterable(termFields)))) } } @@ -531,7 +531,7 @@ sealed trait TermsQuery[S] extends ElasticQuery[S] with HasBoost[TermsQuery[S]] private[elasticsearch] final case class Terms[S]( field: String, - values: List[String], + values: Chunk[String], boost: Option[Double] ) extends TermsQuery[S] { self => def boost(value: Double): TermsQuery[S] = @@ -539,8 +539,8 @@ private[elasticsearch] final case class Terms[S]( def paramsToJson(fieldPath: Option[String]): Json = { val termsFields = - Some(fieldPath.foldRight(field)(_ + "." + _) -> Arr(values.map(Str(_)): _*)) ++ boost.map("boost" -> Num(_)) - Obj("terms" -> Obj(termsFields.toList: _*)) + Some(fieldPath.foldRight(field)(_ + "." + _) -> Arr(values.map(Str(_)))) ++ boost.map("boost" -> Num(_)) + Obj("terms" -> Obj(Chunk.fromIterable(termsFields))) } } @@ -565,6 +565,6 @@ private[elasticsearch] final case class Wildcard[S]( val wildcardFields = Some("value" -> value.toJson) ++ boost.map("boost" -> Num(_)) ++ caseInsensitive.map( "case_insensitive" -> Json.Bool(_) ) - Obj("wildcard" -> Obj(fieldPath.foldRight(field)(_ + "." + _) -> Obj(wildcardFields.toList: _*))) + Obj("wildcard" -> Obj(fieldPath.foldRight(field)(_ + "." + _) -> Obj(Chunk.fromIterable(wildcardFields)))) } } diff --git a/modules/library/src/main/scala/zio/elasticsearch/query/sort/Sort.scala b/modules/library/src/main/scala/zio/elasticsearch/query/sort/Sort.scala index 5941ff93e..d5b6f0955 100644 --- a/modules/library/src/main/scala/zio/elasticsearch/query/sort/Sort.scala +++ b/modules/library/src/main/scala/zio/elasticsearch/query/sort/Sort.scala @@ -16,6 +16,7 @@ package zio.elasticsearch.query.sort +import zio.Chunk import zio.elasticsearch.ElasticPrimitive.ElasticPrimitiveOps import zio.elasticsearch.query.sort.options._ import zio.elasticsearch.script.Script @@ -129,7 +130,7 @@ private[elasticsearch] final case class SortByFieldOptions( self.copy(order = Some(value)) def paramsToJson: Json = { - val allParams = List( + val allParams = Chunk( self.order.map(order => "order" -> order.toString.toJson), self.format.map(format => "format" -> format.toJson), self.numericType.map(numericType => "numeric_type" -> numericType.toString.toJson), @@ -138,7 +139,7 @@ private[elasticsearch] final case class SortByFieldOptions( self.unmappedType.map(unmappedType => "unmapped_type" -> unmappedType.toJson) ).flatten - if (allParams.isEmpty) self.field.toJson else Obj(self.field -> Obj(allParams: _*)) + if (allParams.isEmpty) self.field.toJson else Obj(self.field -> Obj(allParams)) } def unmappedType(value: String): SortByField = @@ -162,12 +163,12 @@ private[elasticsearch] final case class SortByScriptOptions( def paramsToJson: Json = Obj( "_script" -> Obj( - List( + Chunk( Some("type" -> self.sourceType.toString.toJson), Some("script" -> script.toJson), self.order.map(order => "order" -> order.toString.toJson), self.mode.map(mode => "mode" -> mode.toString.toJson) - ).flatten: _* + ).flatten ) ) } diff --git a/modules/library/src/main/scala/zio/elasticsearch/request/options/HasSourceFiltering.scala b/modules/library/src/main/scala/zio/elasticsearch/request/options/HasSourceFiltering.scala index 496d88aea..3a701354c 100644 --- a/modules/library/src/main/scala/zio/elasticsearch/request/options/HasSourceFiltering.scala +++ b/modules/library/src/main/scala/zio/elasticsearch/request/options/HasSourceFiltering.scala @@ -16,6 +16,7 @@ package zio.elasticsearch.request.options +import zio.Chunk import zio.schema.Schema private[elasticsearch] trait HasSourceFiltering[R <: HasSourceFiltering[R]] { @@ -62,15 +63,15 @@ private[elasticsearch] trait HasSourceFiltering[R <: HasSourceFiltering[R]] { */ def includes[A](implicit schema: Schema.Record[A]): R - protected final def getFieldNames(schema: Schema.Record[_]): List[String] = { + protected final def getFieldNames(schema: Schema.Record[_]): Chunk[String] = { def extractInnerSchema(schema: Schema[_]): Schema[_] = Schema.force(schema) match { case schema: Schema.Sequence[_, _, _] => Schema.force(schema.elementSchema) case schema => schema } - def loop(schema: Schema.Record[_], prefix: Option[String]): List[String] = - schema.fields.toList.flatMap { field => + def loop(schema: Schema.Record[_], prefix: Option[String]): Chunk[String] = + schema.fields.flatMap { field => extractInnerSchema(field.schema) match { case schema: Schema.Record[_] => loop(schema, prefix.map(_ + "." + field.name).orElse(Some(field.name))) case _ => List(prefix.fold[String](field.name)(_ + "." + field.name)) diff --git a/modules/library/src/main/scala/zio/elasticsearch/result/ElasticResult.scala b/modules/library/src/main/scala/zio/elasticsearch/result/ElasticResult.scala index 3b4b47282..885f56b46 100644 --- a/modules/library/src/main/scala/zio/elasticsearch/result/ElasticResult.scala +++ b/modules/library/src/main/scala/zio/elasticsearch/result/ElasticResult.scala @@ -20,7 +20,7 @@ import zio.elasticsearch.executor.response.{AggregationResponse, SearchWithAggre import zio.json.ast.Json import zio.prelude.ZValidation import zio.schema.Schema -import zio.{IO, Task, UIO, ZIO} +import zio.{Chunk, IO, Task, UIO, ZIO} private[elasticsearch] sealed trait AggregationsResult { def aggregation(name: String): Task[Option[AggregationResponse]] @@ -58,17 +58,17 @@ final class GetResult private[elasticsearch] (private val doc: Option[Item]) ext } final class SearchResult private[elasticsearch] ( - private val hits: List[Item], + private val hits: Chunk[Item], private val fullResponse: SearchWithAggregationsResponse ) extends DocumentResult[List] { def documentAs[A: Schema]: IO[DecodingException, List[A]] = ZIO.fromEither { - ZValidation.validateAll(hits.map(item => ZValidation.fromEither(item.documentAs))).toEitherWith { errors => + ZValidation.validateAll(hits.map(item => ZValidation.fromEither(item.documentAs)).toList).toEitherWith { errors => DecodingException(s"Could not parse all documents successfully: ${errors.map(_.message).mkString(", ")}") } } - lazy val items: UIO[List[Item]] = ZIO.succeed(hits) + lazy val items: UIO[List[Item]] = ZIO.succeed(hits.toList) lazy val lastSortValue: UIO[Option[Json]] = ZIO.succeed(fullResponse.lastSortField) @@ -78,7 +78,7 @@ final class SearchResult private[elasticsearch] ( } final class SearchAndAggregateResult private[elasticsearch] ( - private val hits: List[Item], + private val hits: Chunk[Item], private val aggs: Map[String, AggregationResponse], private val fullResponse: SearchWithAggregationsResponse ) extends DocumentResult[List] @@ -91,14 +91,14 @@ final class SearchAndAggregateResult private[elasticsearch] ( def documentAs[A: Schema]: Task[List[A]] = ZIO.fromEither { - ZValidation.validateAll(hits.map(item => ZValidation.fromEither(item.documentAs))).toEitherWith { errors => + ZValidation.validateAll(hits.map(item => ZValidation.fromEither(item.documentAs)).toList).toEitherWith { errors => DecodingException( s"Could not parse all documents successfully: ${errors.map(_.message).mkString(",")})" ) } } - lazy val items: UIO[List[Item]] = ZIO.succeed(hits) + lazy val items: UIO[List[Item]] = ZIO.succeed(hits.toList) lazy val lastSortValue: UIO[Option[Json]] = ZIO.succeed(fullResponse.lastSortField) diff --git a/modules/library/src/main/scala/zio/elasticsearch/result/Item.scala b/modules/library/src/main/scala/zio/elasticsearch/result/Item.scala index 5d61663d6..46d7b8f35 100644 --- a/modules/library/src/main/scala/zio/elasticsearch/result/Item.scala +++ b/modules/library/src/main/scala/zio/elasticsearch/result/Item.scala @@ -28,7 +28,7 @@ import zio.schema.codec.JsonCodec.JsonDecoder final case class Item( raw: Json, private val highlight: Option[Json] = None, - private val innerHits: Map[String, List[Json]] = Map.empty, + private val innerHits: Map[String, Chunk[Json]] = Map.empty, sort: Option[Json] = None ) { def documentAs[A](implicit schema: Schema[A]): Either[DecodeError, A] = JsonDecoder.decode(schema, raw.toString) @@ -46,14 +46,15 @@ final case class Item( def innerHitAs[A](name: String)(implicit schema: Schema[A]): Either[DecodingException, List[A]] = for { innerHitsJson <- innerHits.get(name).toRight(DecodingException(s"Could not find inner hits with name $name")) - innerHits <- Validation - .validateAll( - innerHitsJson.map(json => - Validation.fromEither(JsonDecoder.decode(schema, json.toString)).mapError(_.message) - ) - ) - .toEitherWith(errors => - DecodingException(s"Could not parse all documents successfully: ${errors.mkString(", ")}") - ) + innerHits <- + Validation + .validateAll( + innerHitsJson + .map(json => Validation.fromEither(JsonDecoder.decode(schema, json.toString)).mapError(_.message)) + .toList + ) + .toEitherWith(errors => + DecodingException(s"Could not parse all documents successfully: ${errors.mkString(", ")}") + ) } yield innerHits } diff --git a/modules/library/src/main/scala/zio/elasticsearch/script/Script.scala b/modules/library/src/main/scala/zio/elasticsearch/script/Script.scala index 01ce51551..5fc4282f7 100644 --- a/modules/library/src/main/scala/zio/elasticsearch/script/Script.scala +++ b/modules/library/src/main/scala/zio/elasticsearch/script/Script.scala @@ -16,6 +16,7 @@ package zio.elasticsearch.script +import zio.Chunk import zio.elasticsearch.ElasticPrimitive.ElasticPrimitiveOps import zio.elasticsearch.script.options._ import zio.json.ast.Json @@ -31,15 +32,15 @@ private[elasticsearch] final case class Script( self.copy(lang = Some(value)) def withParams(values: (String, Any)*): Script = - self.copy(params = params ++ values.toList) + self.copy(params = params ++ values.toMap) def toJson: Json = Obj( - List( + Chunk( self.lang.map(lang => "lang" -> lang.toJson), Some("source" -> source.toJson), if (params.nonEmpty) { - Some("params" -> Obj(params.map { case (key, value) => + Some("params" -> Obj(Chunk.fromIterable(params).map { case (key, value) => value match { case value: BigDecimal => key -> value.toJson case value: Double => key -> value.toJson @@ -47,11 +48,11 @@ private[elasticsearch] final case class Script( case value: Long => key -> value.toJson case _ => key -> value.toString.toJson } - }.toList: _*)) + })) } else { None } - ).flatten: _* + ).flatten ) } diff --git a/modules/library/src/test/scala/zio/elasticsearch/ElasticAggregationSpec.scala b/modules/library/src/test/scala/zio/elasticsearch/ElasticAggregationSpec.scala index 5f5074d7d..97134a8b3 100644 --- a/modules/library/src/test/scala/zio/elasticsearch/ElasticAggregationSpec.scala +++ b/modules/library/src/test/scala/zio/elasticsearch/ElasticAggregationSpec.scala @@ -112,12 +112,12 @@ object ElasticAggregationSpec extends ZIOSpecDefault { assert(aggregation)( equalTo( Multiple( - List( + Chunk( Terms( name = "first", field = "stringField", order = Chunk(AggregationOrder(value = "_key", order = Desc)), - subAggregations = Nil, + subAggregations = Chunk.empty, size = None ), Max(name = "second", field = "testField", missing = Some(20)), @@ -129,12 +129,12 @@ object ElasticAggregationSpec extends ZIOSpecDefault { assert(aggregationWithSubAggregation)( equalTo( Multiple( - List( + Chunk( Terms( name = "first", field = "testField", order = Chunk.empty, - subAggregations = List( + subAggregations = Chunk( Max( name = "second", field = "intField.raw", @@ -147,7 +147,7 @@ object ElasticAggregationSpec extends ZIOSpecDefault { name = "third", field = "stringField", order = Chunk.empty, - subAggregations = Nil, + subAggregations = Chunk.empty, size = None ) ) @@ -171,12 +171,12 @@ object ElasticAggregationSpec extends ZIOSpecDefault { name = "first", field = "stringField", order = Chunk.empty, - subAggregations = List( + subAggregations = Chunk( Terms( name = "second", field = "stringField.raw", order = Chunk.empty, - subAggregations = Nil, + subAggregations = Chunk.empty, size = None ) ), @@ -186,19 +186,19 @@ object ElasticAggregationSpec extends ZIOSpecDefault { ) && assert(aggregation2)( equalTo( Multiple( - List( + Chunk( Terms( name = "first", field = "stringField", order = Chunk.empty, - subAggregations = Nil, + subAggregations = Chunk.empty, size = None ), Terms( name = "second", field = "testField", order = Chunk.empty, - subAggregations = List( + subAggregations = Chunk( Max( name = "third", field = "anotherTestField", @@ -227,7 +227,13 @@ object ElasticAggregationSpec extends ZIOSpecDefault { assert(aggregation)( equalTo( - Terms(name = "aggregation", field = "testField", order = Chunk.empty, subAggregations = Nil, size = None) + Terms( + name = "aggregation", + field = "testField", + order = Chunk.empty, + subAggregations = Chunk.empty, + size = None + ) ) ) && assert(aggregationTs)( @@ -236,7 +242,7 @@ object ElasticAggregationSpec extends ZIOSpecDefault { name = "aggregation", field = "stringField", order = Chunk.empty, - subAggregations = Nil, + subAggregations = Chunk.empty, size = None ) ) @@ -247,7 +253,7 @@ object ElasticAggregationSpec extends ZIOSpecDefault { name = "aggregation", field = "stringField.raw", order = Chunk.empty, - subAggregations = Nil, + subAggregations = Chunk.empty, size = None ) ) @@ -262,7 +268,7 @@ object ElasticAggregationSpec extends ZIOSpecDefault { AggregationOrder("test", Desc), AggregationOrder("_count", Asc) ), - subAggregations = Nil, + subAggregations = Chunk.empty, size = None ) ) @@ -273,7 +279,7 @@ object ElasticAggregationSpec extends ZIOSpecDefault { name = "aggregation", field = "stringField", order = Chunk.empty, - subAggregations = Nil, + subAggregations = Chunk.empty, size = Some(10) ) ) @@ -284,7 +290,7 @@ object ElasticAggregationSpec extends ZIOSpecDefault { name = "aggregation", field = "stringField.test", order = Chunk(AggregationOrder("_count", Desc), AggregationOrder("_key", Asc)), - subAggregations = Nil, + subAggregations = Chunk.empty, size = Some(5) ) ) diff --git a/modules/library/src/test/scala/zio/elasticsearch/ElasticQuerySpec.scala b/modules/library/src/test/scala/zio/elasticsearch/ElasticQuerySpec.scala index 7a3ea0d54..397410f2f 100644 --- a/modules/library/src/test/scala/zio/elasticsearch/ElasticQuerySpec.scala +++ b/modules/library/src/test/scala/zio/elasticsearch/ElasticQuerySpec.scala @@ -16,6 +16,7 @@ package zio.elasticsearch +import zio.Chunk import zio.elasticsearch.ElasticQuery._ import zio.elasticsearch.ElasticRequest.Bulk import zio.elasticsearch.domain._ @@ -44,13 +45,13 @@ object ElasticQuerySpec extends ZIOSpecDefault { assert(query)( equalTo( Bool[TestDocument]( - filter = List( + filter = Chunk( Match(field = "stringField", value = "test"), Match(field = "testField", value = "test field") ), - must = Nil, - mustNot = Nil, - should = Nil, + must = Chunk.empty, + mustNot = Chunk.empty, + should = Chunk.empty, boost = None, minimumShouldMatch = None ) @@ -58,13 +59,13 @@ object ElasticQuerySpec extends ZIOSpecDefault { ) && assert(queryWithBoost)( equalTo( Bool[TestDocument]( - filter = List( + filter = Chunk( Match(field = "stringField", value = "test"), Match(field = "intField", value = 22) ), - must = Nil, - mustNot = Nil, - should = Nil, + must = Chunk.empty, + mustNot = Chunk.empty, + should = Chunk.empty, boost = Some(10.21), minimumShouldMatch = None ) @@ -79,13 +80,13 @@ object ElasticQuerySpec extends ZIOSpecDefault { assert(query)( equalTo( Bool[TestDocument]( - filter = Nil, - must = List( + filter = Chunk.empty, + must = Chunk( Match(field = "stringField", value = "test"), Match(field = "testField", value = "test field") ), - mustNot = Nil, - should = Nil, + mustNot = Chunk.empty, + should = Chunk.empty, boost = None, minimumShouldMatch = None ) @@ -93,13 +94,13 @@ object ElasticQuerySpec extends ZIOSpecDefault { ) && assert(queryWithBoost)( equalTo( Bool[TestDocument]( - filter = Nil, - must = List( + filter = Chunk.empty, + must = Chunk( Match(field = "stringField.keyword", value = "test"), Match(field = "intField", value = 22) ), - mustNot = Nil, - should = Nil, + mustNot = Chunk.empty, + should = Chunk.empty, boost = Some(10.21), minimumShouldMatch = None ) @@ -115,13 +116,13 @@ object ElasticQuerySpec extends ZIOSpecDefault { assert(query)( equalTo( Bool[TestDocument]( - filter = Nil, - must = Nil, - mustNot = List( + filter = Chunk.empty, + must = Chunk.empty, + mustNot = Chunk( Match(field = "stringField", value = "test"), Match(field = "testField", value = "test field") ), - should = Nil, + should = Chunk.empty, boost = None, minimumShouldMatch = None ) @@ -129,13 +130,13 @@ object ElasticQuerySpec extends ZIOSpecDefault { ) && assert(queryWithBoost)( equalTo( Bool[TestDocument]( - filter = Nil, - must = Nil, - mustNot = List( + filter = Chunk.empty, + must = Chunk.empty, + mustNot = Chunk( Match(field = "stringField.keyword", value = "test"), Match(field = "intField", value = 22) ), - should = Nil, + should = Chunk.empty, boost = Some(10.21), minimumShouldMatch = None ) @@ -160,10 +161,10 @@ object ElasticQuerySpec extends ZIOSpecDefault { assert(query)( equalTo( Bool[TestDocument]( - filter = Nil, - must = Nil, - mustNot = Nil, - should = List( + filter = Chunk.empty, + must = Chunk.empty, + mustNot = Chunk.empty, + should = Chunk( Match(field = "stringField", value = "test"), Match(field = "testField", value = "test field") ), @@ -174,10 +175,10 @@ object ElasticQuerySpec extends ZIOSpecDefault { ) && assert(queryWithBoost)( equalTo( Bool[TestDocument]( - filter = Nil, - must = Nil, - mustNot = Nil, - should = List( + filter = Chunk.empty, + must = Chunk.empty, + mustNot = Chunk.empty, + should = Chunk( Match(field = "stringField.keyword", value = "test"), Match(field = "intField", value = 22) ), @@ -188,10 +189,10 @@ object ElasticQuerySpec extends ZIOSpecDefault { ) && assert(queryWithMinimumShouldMatch)( equalTo( Bool[TestDocument]( - filter = Nil, - must = Nil, - mustNot = Nil, - should = List( + filter = Chunk.empty, + must = Chunk.empty, + mustNot = Chunk.empty, + should = Chunk( Match(field = "stringField.keyword", value = "test"), Match(field = "intField", value = 22), Exists(field = "booleanField") @@ -203,10 +204,10 @@ object ElasticQuerySpec extends ZIOSpecDefault { ) && assert(queryWithAllParams)( equalTo( Bool[TestDocument]( - filter = Nil, - must = Nil, - mustNot = Nil, - should = List( + filter = Chunk.empty, + must = Chunk.empty, + mustNot = Chunk.empty, + should = Chunk( Match(field = "stringField.keyword", value = "test"), Match(field = "intField", value = 22), Exists(field = "booleanField") @@ -232,10 +233,10 @@ object ElasticQuerySpec extends ZIOSpecDefault { assert(query1)( equalTo( Bool[TestDocument]( - filter = List(MatchPhrase(field = "stringField", value = "test")), - must = List(Match(field = "booleanField", value = true)), - mustNot = Nil, - should = Nil, + filter = Chunk(MatchPhrase(field = "stringField", value = "test")), + must = Chunk(Match(field = "booleanField", value = true)), + mustNot = Chunk.empty, + should = Chunk.empty, boost = None, minimumShouldMatch = None ) @@ -244,14 +245,14 @@ object ElasticQuerySpec extends ZIOSpecDefault { assert(query2)( equalTo( Bool[TestDocument]( - filter = Nil, - must = List(Terms(field = "stringField", values = List("a", "b", "c"), boost = None)), - mustNot = List( + filter = Chunk.empty, + must = Chunk(Terms(field = "stringField", values = Chunk("a", "b", "c"), boost = None)), + mustNot = Chunk( Match(field = "doubleField", value = 3.14), Match(field = "testField", value = true), Exists("anotherTestField") ), - should = Nil, + should = Chunk.empty, boost = None, minimumShouldMatch = None ) @@ -260,10 +261,10 @@ object ElasticQuerySpec extends ZIOSpecDefault { assert(query3)( equalTo( Bool[TestDocument]( - filter = Nil, - must = List(Terms(field = "stringField", values = List("a", "b", "c"), boost = None)), - mustNot = List(Match(field = "intField", value = 50)), - should = List( + filter = Chunk.empty, + must = Chunk(Terms(field = "stringField", values = Chunk("a", "b", "c"), boost = None)), + mustNot = Chunk(Match(field = "intField", value = 50)), + should = Chunk( Range( field = "intField", lower = GreaterThan(1), @@ -281,10 +282,10 @@ object ElasticQuerySpec extends ZIOSpecDefault { assert(queryWithBoost)( equalTo( Bool[TestDocument]( - filter = List(MatchPhrase(field = "stringField", value = "test")), - must = List(Match(field = "booleanField", value = true)), - mustNot = Nil, - should = Nil, + filter = Chunk(MatchPhrase(field = "stringField", value = "test")), + must = Chunk(Match(field = "booleanField", value = true)), + mustNot = Chunk.empty, + should = Chunk.empty, boost = Some(3.14), minimumShouldMatch = None ) @@ -293,14 +294,14 @@ object ElasticQuerySpec extends ZIOSpecDefault { assert(queryWithMinimumShouldMatch)( equalTo( Bool[TestDocument]( - filter = Nil, - must = List(Terms(field = "stringField", values = List("a", "b", "c"), boost = None)), - mustNot = List( + filter = Chunk.empty, + must = Chunk(Terms(field = "stringField", values = Chunk("a", "b", "c"), boost = None)), + mustNot = Chunk( Match(field = "doubleField", value = 3.14), Match(field = "testField", value = true), Exists("anotherTestField") ), - should = Nil, + should = Chunk.empty, boost = None, minimumShouldMatch = Some(2) ) @@ -309,10 +310,10 @@ object ElasticQuerySpec extends ZIOSpecDefault { assert(queryWithAllParams)( equalTo( Bool[TestDocument]( - filter = Nil, - must = List(Terms(field = "stringField", values = List("a", "b", "c"), boost = None)), - mustNot = List(Match(field = "intField", value = 50)), - should = List( + filter = Chunk.empty, + must = Chunk(Terms(field = "stringField", values = Chunk("a", "b", "c"), boost = None)), + mustNot = Chunk(Match(field = "intField", value = 50)), + should = Chunk( Range( field = "intField", lower = GreaterThan(1), @@ -1028,15 +1029,15 @@ object ElasticQuerySpec extends ZIOSpecDefault { val queryWithSuffix = terms(TestDocument.stringField.keyword, "a", "b", "c") val queryWithBoost = terms(TestDocument.stringField, "a", "b", "c").boost(10.21) - assert(query)(equalTo(Terms[Any](field = "stringField", values = List("a", "b", "c"), boost = None))) && + assert(query)(equalTo(Terms[Any](field = "stringField", values = Chunk("a", "b", "c"), boost = None))) && assert(queryTs)( - equalTo(Terms[TestDocument](field = "stringField", values = List("a", "b", "c"), boost = None)) + equalTo(Terms[TestDocument](field = "stringField", values = Chunk("a", "b", "c"), boost = None)) ) && assert(queryWithSuffix)( - equalTo(Terms[TestDocument](field = "stringField.keyword", values = List("a", "b", "c"), boost = None)) + equalTo(Terms[TestDocument](field = "stringField.keyword", values = Chunk("a", "b", "c"), boost = None)) ) && assert(queryWithBoost)( - equalTo(Terms[TestDocument](field = "stringField", values = List("a", "b", "c"), boost = Some(10.21))) + equalTo(Terms[TestDocument](field = "stringField", values = Chunk("a", "b", "c"), boost = Some(10.21))) ) }, test("wildcard") { diff --git a/modules/library/src/test/scala/zio/elasticsearch/HttpElasticExecutorSpec.scala b/modules/library/src/test/scala/zio/elasticsearch/HttpElasticExecutorSpec.scala index 8d73b2e4d..4705fcdfd 100644 --- a/modules/library/src/test/scala/zio/elasticsearch/HttpElasticExecutorSpec.scala +++ b/modules/library/src/test/scala/zio/elasticsearch/HttpElasticExecutorSpec.scala @@ -16,6 +16,7 @@ package zio.elasticsearch +import zio.Chunk import zio.elasticsearch.ElasticAggregation.termsAggregation import zio.elasticsearch.ElasticQuery.{matchAll, term} import zio.elasticsearch.domain.TestDocument @@ -47,7 +48,7 @@ object HttpElasticExecutorSpec extends SttpBackendStubSpec { ) .aggregations )( - equalTo(Map("aggregation1" -> TermsAggregationResponse(0, 0, List(TermsAggregationBucket("name", 5, None))))) + equalTo(Map("aggregation1" -> TermsAggregationResponse(0, 0, Chunk(TermsAggregationBucket("name", 5, None))))) ) }, test("bulk request") { @@ -58,7 +59,7 @@ object HttpElasticExecutorSpec extends SttpBackendStubSpec { BulkResponse( took = 3, errors = false, - items = List( + items = Chunk( CreateBulkResponse( index = "repositories", id = "123", @@ -200,7 +201,7 @@ object HttpElasticExecutorSpec extends SttpBackendStubSpec { .execute(ElasticRequest.search(index = index, query = matchAll, terms)) assertZIO(req.documentAs[TestDocument])(equalTo(List(doc))) && assertZIO(req.aggregations)( - equalTo(Map("aggregation1" -> TermsAggregationResponse(0, 0, List(TermsAggregationBucket("name", 5, None))))) + equalTo(Map("aggregation1" -> TermsAggregationResponse(0, 0, Chunk(TermsAggregationBucket("name", 5, None))))) ) }, test("update request with script") { diff --git a/modules/library/src/test/scala/zio/elasticsearch/SortSpec.scala b/modules/library/src/test/scala/zio/elasticsearch/SortSpec.scala index 1ddf47b99..524263be3 100644 --- a/modules/library/src/test/scala/zio/elasticsearch/SortSpec.scala +++ b/modules/library/src/test/scala/zio/elasticsearch/SortSpec.scala @@ -1,6 +1,5 @@ package zio.elasticsearch -import zio.Scope import zio.elasticsearch.ElasticSort._ import zio.elasticsearch.domain._ import zio.elasticsearch.query.sort.Missing._ @@ -15,6 +14,7 @@ import zio.json.ast.Json import zio.json.ast.Json.{Arr, Obj} import zio.test.Assertion.equalTo import zio.test._ +import zio.{Chunk, Scope} object SortSpec extends ZIOSpecDefault { def spec: Spec[Environment with TestEnvironment with Scope, Any] = @@ -525,5 +525,5 @@ object SortSpec extends ZIOSpecDefault { ) ) - private def sortsToJson(sorts: Sort*): Json = Obj("sort" -> Arr(sorts.map(_.paramsToJson): _*)) + private def sortsToJson(sorts: Sort*): Json = Obj("sort" -> Arr(Chunk.fromIterable(sorts).map(_.paramsToJson))) }