From ae06779555b2fe3a6cad3a27b91d243bf877590b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20H=C3=B8ydahl?= Date: Thu, 24 Sep 2026 17:47:18 +0200 Subject: [PATCH 1/8] SOLR-18479: Add v2 copy-field endpoints to the Schema API Fields, dynamic fields and field types each have PUT/DELETE routes in the v2 Schema API; copy-fields were the one resource left reachable only through /schema/bulk. The routes had been sketched out and commented out, with a TODO noting that copy-field rules have no name to address them by. Address them by source field instead: PUT /schema/copyfields/{sourceField} takes a destinations list in the body, and DELETE removes every rule with that source unless 'destination' query parameters narrow the selection. Deleting a source that has no rules answers 404 rather than silently succeeding. The source-addressed shape means one request covers a 1:many fan-out, at the cost of the path naming a set of rules rather than a single one. Enumerating the destinations for an unqualified DELETE goes through IndexSchema.getCopyFieldProperties so that glob rules are covered as well as explicit ones. The ref guide's v2 copy-field examples are updated to the new endpoints; they previously showed a v1 keyed-object body POSTed to /schema, which that path answers with a 405 since it only carries GET. --- .../SOLR-18479-v2-copyfield-api.yml | 12 ++ .../client/api/endpoint/UpdateSchemaApi.java | 46 +++-- .../solr/handler/admin/api/UpdateSchema.java | 66 +++++++ .../handler/admin/api/V2CopyFieldApiTest.java | 177 ++++++++++++++++++ .../api/V2UpdateSchemaErrorCaseTests.java | 38 ++++ .../indexing-guide/pages/schema-api.adoc | 21 ++- 6 files changed, 333 insertions(+), 27 deletions(-) create mode 100644 changelog/unreleased/SOLR-18479-v2-copyfield-api.yml create mode 100644 solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java diff --git a/changelog/unreleased/SOLR-18479-v2-copyfield-api.yml b/changelog/unreleased/SOLR-18479-v2-copyfield-api.yml new file mode 100644 index 000000000000..1dc3a6e307be --- /dev/null +++ b/changelog/unreleased/SOLR-18479-v2-copyfield-api.yml @@ -0,0 +1,12 @@ +title: > + The v2 Schema API can now add and remove copy-field rules directly, via + `PUT` and `DELETE` on `/api/collections//schema/copyfields/`. + Previously copy-fields were the one schema resource reachable only through the bulk endpoint. + Rules are addressed by their source field: the `PUT` body carries a `destinations` list, and + `DELETE` removes every rule with that source unless `destination` query parameters narrow it. +type: added +authors: + - name: Jan Høydahl +links: + - name: SOLR-18479 + url: https://issues.apache.org/jira/browse/SOLR-18479 diff --git a/solr/api/src/java/org/apache/solr/client/api/endpoint/UpdateSchemaApi.java b/solr/api/src/java/org/apache/solr/client/api/endpoint/UpdateSchemaApi.java index 5b5971928f3d..7e0a1f123c07 100644 --- a/solr/api/src/java/org/apache/solr/client/api/endpoint/UpdateSchemaApi.java +++ b/solr/api/src/java/org/apache/solr/client/api/endpoint/UpdateSchemaApi.java @@ -28,7 +28,9 @@ import jakarta.ws.rs.PUT; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.QueryParam; import java.util.List; +import org.apache.solr.client.api.model.AddCopyFieldOperation; import org.apache.solr.client.api.model.SchemaChange; import org.apache.solr.client.api.model.SolrJerseyResponse; import org.apache.solr.client.api.model.UpsertDynamicFieldOperation; @@ -112,25 +114,31 @@ SolrJerseyResponse addFieldType( SolrJerseyResponse deleteFieldType(@PathParam("fieldTypeName") String fieldTypeName) throws Exception; - // TODO Gah! Copyfields don't currently have names for us to create/delete by name in an API like - // /schema/copyfields/{copyFieldName}...figure out how to address this in a way consistent with - // all our other APIs. (In the meantime, the functionality is exposed through the bulk API at - // least. - // @POST - // @Path("/copyfields/{copyFieldName}") - // @StoreApiParameters - // @Operation( - // summary = "Add a new copy-field with the specified name.", - // tags = {"schema"}) - // SolrJerseyResponse addCopyField(@PathParam("copyFieldName") String copyFieldName, - // @RequestBody SchemaChangeOperation.AddCopyField requestBody) throws Exception; - // - // @DELETE - // @Path("/copyfields/{copyFieldName}") - // @StoreApiParameters - // @Operation(summary = "Remove the copy-field with the specified name.", tags = {"schema"}) - // SolrJerseyResponse deleteCopyField(@PathParam("copyFieldName") String copyFieldName) throws - // Exception; + // Copy-field rules have no name of their own, so unlike the other schema resources they are + // addressed by their source field. A single request therefore covers all of the rules that + // share that source. + @PUT + @Path("/copyfields/{sourceField}") + @StoreApiParameters + @Operation( + summary = "Add copy-field rules copying from the specified source field.", + tags = {"schema"}) + SolrJerseyResponse addCopyField( + @PathParam("sourceField") String sourceField, @RequestBody AddCopyFieldOperation requestBody) + throws Exception; + + @DELETE + @Path("/copyfields/{sourceField}") + @StoreApiParameters + @Operation( + summary = + "Remove copy-field rules copying from the specified source field. Removes every rule " + + "with that source unless 'destination' query parameters narrow the selection.", + tags = {"schema"}) + SolrJerseyResponse deleteCopyField( + @PathParam("sourceField") String sourceField, + @QueryParam("destination") List destinations) + throws Exception; @POST @Path("/bulk") diff --git a/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java b/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java index 55b66b4bed5e..d6a74bde497a 100644 --- a/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java +++ b/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java @@ -21,10 +21,13 @@ import jakarta.inject.Inject; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.solr.api.JerseyResource; import org.apache.solr.client.api.endpoint.UpdateSchemaApi; +import org.apache.solr.client.api.model.AddCopyFieldOperation; +import org.apache.solr.client.api.model.DeleteCopyFieldOperation; import org.apache.solr.client.api.model.DeleteDynamicFieldOperation; import org.apache.solr.client.api.model.DeleteFieldOperation; import org.apache.solr.client.api.model.DeleteFieldTypeOperation; @@ -39,6 +42,7 @@ import org.apache.solr.handler.SolrConfigHandler; import org.apache.solr.jersey.PermissionName; import org.apache.solr.request.SolrQueryRequest; +import org.apache.solr.schema.IndexSchema; import org.apache.solr.schema.SchemaManager; import org.apache.solr.security.PermissionNameProvider; @@ -151,6 +155,68 @@ public SolrJerseyResponse deleteFieldType(String fieldTypeName) throws Exception return response; } + @Override + @PermissionName(PermissionNameProvider.Name.SCHEMA_EDIT_PERM) + public SolrJerseyResponse addCopyField(String sourceField, AddCopyFieldOperation requestBody) + throws Exception { + final var response = instantiateJerseyResponse(SolrJerseyResponse.class); + ensureSchemaMutable(); + ensureRequiredParameterProvided("sourceField", sourceField); + ensureRequiredRequestBodyProvided(requestBody); + ensureRequiredParameterProvided("destinations", requestBody.destinations); + requestBody.source = sourceField; + requestBody.operationType = "add-copy-field"; + + runWithSchemaManager(List.of(requestBody)); + + return response; + } + + @Override + @PermissionName(PermissionNameProvider.Name.SCHEMA_EDIT_PERM) + public SolrJerseyResponse deleteCopyField(String sourceField, List destinations) + throws Exception { + final var response = instantiateJerseyResponse(SolrJerseyResponse.class); + ensureSchemaMutable(); + ensureRequiredParameterProvided("sourceField", sourceField); + + // An unqualified DELETE removes every rule with the given source; 'destination' params narrow + // that to specific rules. + final var toDelete = + (destinations == null || destinations.isEmpty()) + ? currentDestinationsOf(sourceField) + : destinations; + if (toDelete.isEmpty()) { + throw new SolrException( + SolrException.ErrorCode.NOT_FOUND, + "No copy-field rules found with source '" + sourceField + "'"); + } + + final var deleteCopyFieldOp = new DeleteCopyFieldOperation(); + deleteCopyFieldOp.operationType = "delete-copy-field"; + deleteCopyFieldOp.source = sourceField; + deleteCopyFieldOp.destinations = toDelete; + + runWithSchemaManager(List.of(deleteCopyFieldOp)); + + return response; + } + + /** + * Lists the destinations of every copy-field rule currently declared with the given source. + * + *

Covers dynamic (i.e. glob) rules as well as explicit ones, since either may be addressed by + * source. + */ + private List currentDestinationsOf(String sourceField) { + return solrCore + .getLatestSchema() + .getCopyFieldProperties(false, Set.of(sourceField), null) + .stream() + .map(properties -> (String) properties.get(IndexSchema.DESTINATION)) + .collect(Collectors.toList()); + } + @Override @PermissionName(PermissionNameProvider.Name.SCHEMA_EDIT_PERM) public SolrJerseyResponse bulkSchemaModification(List requestBody) diff --git a/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java b/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java new file mode 100644 index 000000000000..f4f43fec2d1a --- /dev/null +++ b/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java @@ -0,0 +1,177 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.solr.handler.admin.api; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import org.apache.solr.client.solrj.RemoteSolrException; +import org.apache.solr.client.solrj.request.CollectionAdminRequest; +import org.apache.solr.client.solrj.request.V2Request; +import org.apache.solr.cloud.SolrCloudTestCase; +import org.apache.solr.common.params.MapSolrParams; +import org.apache.solr.common.params.ModifiableSolrParams; +import org.apache.solr.common.util.NamedList; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +/** Tests the v2 copy-field endpoints, which address rules by their source field. */ +public class V2CopyFieldApiTest extends SolrCloudTestCase { + + private static final String COLLECTION = "v2CopyFieldApiTest"; + private static final String SOURCE = "cf_source"; + private static final String DEST_ONE = "cf_dest_one"; + private static final String DEST_TWO = "cf_dest_two"; + + @BeforeClass + public static void setupCluster() throws Exception { + System.setProperty("managed.schema.mutable", "true"); + configureCluster(1).addConfig("conf", configset("cloud-managed")).configure(); + + CollectionAdminRequest.createCollection(COLLECTION, "conf", 1, 1) + .process(cluster.getSolrClient()); + cluster.waitForActiveCollection(COLLECTION, 1, 1); + + for (String field : List.of(SOURCE, DEST_ONE, DEST_TWO)) { + new V2Request.Builder(schemaPath("/fields/" + field)) + .PUT() + .withPayload(Map.of("type", "string", "multiValued", true)) + .build() + .process(cluster.getSolrClient()); + } + } + + @Before + public void clearCopyFields() throws Exception { + // Leave each test a clean slate; the source may legitimately have no rules yet. + try { + deleteCopyFields(SOURCE); + } catch (RemoteSolrException e) { + if (e.code() != 404) { + throw e; + } + } + } + + private static String schemaPath(String suffix) { + return "/collections/" + COLLECTION + "/schema" + suffix; + } + + private static void addCopyFields(String source, Object payload) throws Exception { + new V2Request.Builder(schemaPath("/copyfields/" + source)) + .PUT() + .withPayload(payload) + .build() + .process(cluster.getSolrClient()); + } + + private static void deleteCopyFields(String source, String... destinations) throws Exception { + final var params = new ModifiableSolrParams(); + for (String destination : destinations) { + params.add("destination", destination); + } + new V2Request.Builder(schemaPath("/copyfields/" + source)) + .DELETE() + .withParams(params) + .build() + .process(cluster.getSolrClient()); + } + + /** Destinations of every copy-field rule currently declared with the given source. */ + @SuppressWarnings("unchecked") + private static List destinationsOf(String source) throws Exception { + final var response = + new V2Request.Builder(schemaPath("/copyfields")) + .GET() + .withParams(new MapSolrParams(Map.of())) + .build() + .process(cluster.getSolrClient()); + final var copyFields = (List>) response.getResponse().get("copyFields"); + return copyFields.stream() + .filter(rule -> source.equals(rule.get("source"))) + .map(rule -> (String) rule.get("dest")) + .sorted() + .collect(Collectors.toList()); + } + + @Test + public void testAddAndListCopyFieldsBySource() throws Exception { + addCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + + assertEquals(List.of(DEST_ONE, DEST_TWO), destinationsOf(SOURCE)); + } + + @Test + public void testAddAcceptsSingleDestinationAndMaxChars() throws Exception { + addCopyFields(SOURCE, Map.of("destinations", DEST_ONE, "maxChars", 100)); + + assertEquals(List.of(DEST_ONE), destinationsOf(SOURCE)); + } + + @Test + public void testDeleteNarrowedByDestinationParam() throws Exception { + addCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + + deleteCopyFields(SOURCE, DEST_ONE); + + assertEquals( + "only the named destination should have been removed", + List.of(DEST_TWO), + destinationsOf(SOURCE)); + } + + @Test + public void testUnqualifiedDeleteRemovesEveryRuleForTheSource() throws Exception { + addCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + + deleteCopyFields(SOURCE); + + assertEquals(List.of(), destinationsOf(SOURCE)); + } + + @Test + public void testDeleteLeavesRulesWithOtherSourcesAlone() throws Exception { + addCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); + + deleteCopyFields(SOURCE); + + // 'id' -> 'id_prefix' is declared by the cloud-managed configset itself. + assertEquals(List.of("id_prefix"), destinationsOf("id")); + } + + @Test + public void testDeleteOfUnknownSourceIsNotFound() throws Exception { + final var thrown = + expectThrows(RemoteSolrException.class, () -> deleteCopyFields("no_such_source_field")); + + assertEquals(404, thrown.code()); + assertTrue( + "unexpected message: " + thrown.getMessage(), + thrown.getMessage().contains("No copy-field rules found")); + } + + @Test + public void testAddRequiresDestinations() throws Exception { + final var thrown = + expectThrows(RemoteSolrException.class, () -> addCopyFields(SOURCE, new NamedList<>())); + + assertEquals(400, thrown.code()); + assertTrue( + "unexpected message: " + thrown.getMessage(), thrown.getMessage().contains("destinations")); + } +} diff --git a/solr/core/src/test/org/apache/solr/handler/admin/api/V2UpdateSchemaErrorCaseTests.java b/solr/core/src/test/org/apache/solr/handler/admin/api/V2UpdateSchemaErrorCaseTests.java index d981f572a0b1..4f6c594bf079 100644 --- a/solr/core/src/test/org/apache/solr/handler/admin/api/V2UpdateSchemaErrorCaseTests.java +++ b/solr/core/src/test/org/apache/solr/handler/admin/api/V2UpdateSchemaErrorCaseTests.java @@ -21,7 +21,9 @@ import static org.hamcrest.Matchers.containsString; import static org.mockito.Mockito.mock; +import java.util.List; import org.apache.solr.SolrTestCase; +import org.apache.solr.client.api.model.AddCopyFieldOperation; import org.apache.solr.client.api.model.UpsertDynamicFieldOperation; import org.apache.solr.client.api.model.UpsertFieldOperation; import org.apache.solr.client.api.model.UpsertFieldTypeOperation; @@ -155,4 +157,40 @@ public void testDeleteFieldTypeOperationRequiresTypeName() { assertEquals(BAD_REQUEST.code, thrown.code()); assertThat(thrown.getMessage(), containsString("Missing required parameter: fieldTypeName")); } + + @Test + public void testAddCopyFieldOperationRequiresSourceAndDestinations() { + final var noSourceOp = new AddCopyFieldOperation(); + noSourceOp.destinations = List.of("someDestination"); + var thrown = + expectThrows( + SolrException.class, + () -> { + schemaApi.addCopyField(null, noSourceOp); + }); + assertEquals(BAD_REQUEST.code, thrown.code()); + assertThat(thrown.getMessage(), containsString("Missing required parameter: sourceField")); + + final var noDestinationsOp = new AddCopyFieldOperation(); + thrown = + expectThrows( + SolrException.class, + () -> { + schemaApi.addCopyField("someSourceField", noDestinationsOp); + }); + assertEquals(BAD_REQUEST.code, thrown.code()); + assertThat(thrown.getMessage(), containsString("Missing required parameter: destinations")); + } + + @Test + public void testDeleteCopyFieldOperationRequiresSource() { + var thrown = + expectThrows( + SolrException.class, + () -> { + schemaApi.deleteCopyField(null, List.of("someDestination")); + }); + assertEquals(BAD_REQUEST.code, thrown.code()); + assertThat(thrown.getMessage(), containsString("Missing required parameter: sourceField")); + } } diff --git a/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc b/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc index aa4047dc2926..cc5f7e172ec9 100644 --- a/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc +++ b/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc @@ -523,14 +523,17 @@ V2 API:: ==== [source,bash] ---- -curl -X POST -H 'Content-type:application/json' --data-binary '{ - "add-copy-field":{ - "source":"shelf", - "dest":[ "location", "catchall" ]} -}' http://localhost:8983/api/collections/techproducts/schema +curl -X PUT -H 'Content-type:application/json' --data-binary ' +{ + "destinations":[ "location", "catchall" ] +}' http://localhost:8983/api/collections/techproducts/schema/copyfields/shelf ---- ==== ====== ++ +Copy-field rules have no name of their own, so v2 addresses them by their source field: the source +is the final path segment, and the body carries the destinations. +The v2 request attribute is `destinations`, though `dest` is accepted as an alias. === Delete a Copy Field Rule @@ -559,12 +562,14 @@ V2 API:: ==== [source,bash] ---- -curl -X POST -H 'Content-type:application/json' --data-binary '{ - "delete-copy-field":{ "source":"shelf", "dest":"location" } -}' http://localhost:8983/api/collections/techproducts/schema +curl -X DELETE "http://localhost:8983/api/collections/techproducts/schema/copyfields/shelf?destination=location" ---- ==== ====== ++ +Repeat the `destination` parameter to remove several rules at once. +Omitting it entirely removes *every* rule with that source. +Deleting a source that has no copy-field rules returns a 404. === Multiple Commands in a Single POST From c31eb34c6d23fb9b99afd9d183ab762e4b8c83b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20H=C3=B8ydahl?= Date: Thu, 24 Sep 2026 18:12:52 +0200 Subject: [PATCH 2/8] SOLR-18479: Make the v2 copy-field PUT idempotent The underlying 'add-copy-field' operation is purely additive: registerCopyField appends a rule without checking whether an identical one is already present, so PUTting the same destinations twice left the source copied twice over at index time. That breaks PUT's idempotency contract, and it also meant the body could only ever state the rules being added rather than the rules the caller wanted. Clear the source's existing rules as part of the same SchemaManager operation list, so the destinations in the body become the complete set for that source. Applying both operations as a unit keeps the change transactional: a rejected replacement leaves the previous rules in place. Renamed the endpoint method to upsertCopyFields, since 'add' no longer describes what it does. Adding a destination while keeping the others now means either listing them all, or using add-copy-field through the bulk endpoint, which still only appends; the ref guide spells out both, along with the duplicate hazard of the additive operation. --- .../SOLR-18479-v2-copyfield-api.yml | 9 +-- .../client/api/endpoint/UpdateSchemaApi.java | 6 +- .../solr/handler/admin/api/UpdateSchema.java | 21 ++++++- .../handler/admin/api/V2CopyFieldApiTest.java | 59 ++++++++++++++++--- .../api/V2UpdateSchemaErrorCaseTests.java | 6 +- .../indexing-guide/pages/schema-api.adoc | 12 ++++ 6 files changed, 95 insertions(+), 18 deletions(-) diff --git a/changelog/unreleased/SOLR-18479-v2-copyfield-api.yml b/changelog/unreleased/SOLR-18479-v2-copyfield-api.yml index 1dc3a6e307be..2b23c08d1ddf 100644 --- a/changelog/unreleased/SOLR-18479-v2-copyfield-api.yml +++ b/changelog/unreleased/SOLR-18479-v2-copyfield-api.yml @@ -1,9 +1,10 @@ title: > - The v2 Schema API can now add and remove copy-field rules directly, via - `PUT` and `DELETE` on `/api/collections//schema/copyfields/`. + The v2 Schema API can now manage copy-field rules directly, via `PUT` and `DELETE` on + `/api/collections//schema/copyfields/`. Previously copy-fields were the one schema resource reachable only through the bulk endpoint. - Rules are addressed by their source field: the `PUT` body carries a `destinations` list, and - `DELETE` removes every rule with that source unless `destination` query parameters narrow it. + Rules are addressed by their source field: `PUT` sets the complete `destinations` list for that + source, replacing any rules it already had, and `DELETE` removes every rule with that source + unless `destination` query parameters narrow it. type: added authors: - name: Jan Høydahl diff --git a/solr/api/src/java/org/apache/solr/client/api/endpoint/UpdateSchemaApi.java b/solr/api/src/java/org/apache/solr/client/api/endpoint/UpdateSchemaApi.java index 7e0a1f123c07..0184c3b9df36 100644 --- a/solr/api/src/java/org/apache/solr/client/api/endpoint/UpdateSchemaApi.java +++ b/solr/api/src/java/org/apache/solr/client/api/endpoint/UpdateSchemaApi.java @@ -121,9 +121,11 @@ SolrJerseyResponse deleteFieldType(@PathParam("fieldTypeName") String fieldTypeN @Path("/copyfields/{sourceField}") @StoreApiParameters @Operation( - summary = "Add copy-field rules copying from the specified source field.", + summary = + "Set the copy-field rules for the specified source field. The given destinations " + + "replace any rules that source already has.", tags = {"schema"}) - SolrJerseyResponse addCopyField( + SolrJerseyResponse upsertCopyFields( @PathParam("sourceField") String sourceField, @RequestBody AddCopyFieldOperation requestBody) throws Exception; diff --git a/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java b/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java index d6a74bde497a..3f4e09fafb22 100644 --- a/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java +++ b/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java @@ -19,6 +19,7 @@ import static org.apache.solr.common.util.CommandOperation.ERR_MSGS; import jakarta.inject.Inject; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; @@ -157,7 +158,7 @@ public SolrJerseyResponse deleteFieldType(String fieldTypeName) throws Exception @Override @PermissionName(PermissionNameProvider.Name.SCHEMA_EDIT_PERM) - public SolrJerseyResponse addCopyField(String sourceField, AddCopyFieldOperation requestBody) + public SolrJerseyResponse upsertCopyFields(String sourceField, AddCopyFieldOperation requestBody) throws Exception { final var response = instantiateJerseyResponse(SolrJerseyResponse.class); ensureSchemaMutable(); @@ -167,7 +168,23 @@ public SolrJerseyResponse addCopyField(String sourceField, AddCopyFieldOperation requestBody.source = sourceField; requestBody.operationType = "add-copy-field"; - runWithSchemaManager(List.of(requestBody)); + // 'add-copy-field' is purely additive: it appends a rule without checking whether an identical + // one is already present, so repeating it would silently copy the source twice over. Clearing + // the source's existing rules first is what makes this PUT idempotent, and lets the body state + // the rules the caller wants rather than only the ones being added. + final var operations = new ArrayList(); + final var existing = currentDestinationsOf(sourceField); + if (!existing.isEmpty()) { + final var replacedOp = new DeleteCopyFieldOperation(); + replacedOp.operationType = "delete-copy-field"; + replacedOp.source = sourceField; + replacedOp.destinations = existing; + operations.add(replacedOp); + } + operations.add(requestBody); + + // SchemaManager applies the list as a unit, so a failure to add leaves the old rules in place. + runWithSchemaManager(operations); return response; } diff --git a/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java b/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java index f4f43fec2d1a..37e23395022b 100644 --- a/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java +++ b/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java @@ -72,7 +72,7 @@ private static String schemaPath(String suffix) { return "/collections/" + COLLECTION + "/schema" + suffix; } - private static void addCopyFields(String source, Object payload) throws Exception { + private static void putCopyFields(String source, Object payload) throws Exception { new V2Request.Builder(schemaPath("/copyfields/" + source)) .PUT() .withPayload(payload) @@ -111,21 +111,66 @@ private static List destinationsOf(String source) throws Exception { @Test public void testAddAndListCopyFieldsBySource() throws Exception { - addCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); assertEquals(List.of(DEST_ONE, DEST_TWO), destinationsOf(SOURCE)); } + @Test + public void testRepeatedPutIsIdempotent() throws Exception { + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + + // 'add-copy-field' on its own would append a second, duplicate rule for each destination, + // making the source get copied twice over at index time. + assertEquals(List.of(DEST_ONE, DEST_TWO), destinationsOf(SOURCE)); + } + + @Test + public void testPutReplacesTheSourcesExistingRules() throws Exception { + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_TWO))); + + assertEquals( + "destinations left out of the request should be gone", + List.of(DEST_TWO), + destinationsOf(SOURCE)); + } + + @Test + public void testPutCanExtendTheSourcesExistingRules() throws Exception { + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); + + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + + assertEquals(List.of(DEST_ONE, DEST_TWO), destinationsOf(SOURCE)); + } + + @Test + public void testFailedPutLeavesExistingRulesIntact() throws Exception { + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); + + expectThrows( + RemoteSolrException.class, + () -> putCopyFields(SOURCE, Map.of("destinations", List.of("no_such_destination_field")))); + + assertEquals( + "a rejected replacement must not drop the rules it would have replaced", + List.of(DEST_ONE), + destinationsOf(SOURCE)); + } + @Test public void testAddAcceptsSingleDestinationAndMaxChars() throws Exception { - addCopyFields(SOURCE, Map.of("destinations", DEST_ONE, "maxChars", 100)); + putCopyFields(SOURCE, Map.of("destinations", DEST_ONE, "maxChars", 100)); assertEquals(List.of(DEST_ONE), destinationsOf(SOURCE)); } @Test public void testDeleteNarrowedByDestinationParam() throws Exception { - addCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); deleteCopyFields(SOURCE, DEST_ONE); @@ -137,7 +182,7 @@ public void testDeleteNarrowedByDestinationParam() throws Exception { @Test public void testUnqualifiedDeleteRemovesEveryRuleForTheSource() throws Exception { - addCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); deleteCopyFields(SOURCE); @@ -146,7 +191,7 @@ public void testUnqualifiedDeleteRemovesEveryRuleForTheSource() throws Exception @Test public void testDeleteLeavesRulesWithOtherSourcesAlone() throws Exception { - addCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); deleteCopyFields(SOURCE); @@ -168,7 +213,7 @@ public void testDeleteOfUnknownSourceIsNotFound() throws Exception { @Test public void testAddRequiresDestinations() throws Exception { final var thrown = - expectThrows(RemoteSolrException.class, () -> addCopyFields(SOURCE, new NamedList<>())); + expectThrows(RemoteSolrException.class, () -> putCopyFields(SOURCE, new NamedList<>())); assertEquals(400, thrown.code()); assertTrue( diff --git a/solr/core/src/test/org/apache/solr/handler/admin/api/V2UpdateSchemaErrorCaseTests.java b/solr/core/src/test/org/apache/solr/handler/admin/api/V2UpdateSchemaErrorCaseTests.java index 4f6c594bf079..490a6b65ae3e 100644 --- a/solr/core/src/test/org/apache/solr/handler/admin/api/V2UpdateSchemaErrorCaseTests.java +++ b/solr/core/src/test/org/apache/solr/handler/admin/api/V2UpdateSchemaErrorCaseTests.java @@ -159,14 +159,14 @@ public void testDeleteFieldTypeOperationRequiresTypeName() { } @Test - public void testAddCopyFieldOperationRequiresSourceAndDestinations() { + public void testUpsertCopyFieldsOperationRequiresSourceAndDestinations() { final var noSourceOp = new AddCopyFieldOperation(); noSourceOp.destinations = List.of("someDestination"); var thrown = expectThrows( SolrException.class, () -> { - schemaApi.addCopyField(null, noSourceOp); + schemaApi.upsertCopyFields(null, noSourceOp); }); assertEquals(BAD_REQUEST.code, thrown.code()); assertThat(thrown.getMessage(), containsString("Missing required parameter: sourceField")); @@ -176,7 +176,7 @@ public void testAddCopyFieldOperationRequiresSourceAndDestinations() { expectThrows( SolrException.class, () -> { - schemaApi.addCopyField("someSourceField", noDestinationsOp); + schemaApi.upsertCopyFields("someSourceField", noDestinationsOp); }); assertEquals(BAD_REQUEST.code, thrown.code()); assertThat(thrown.getMessage(), containsString("Missing required parameter: destinations")); diff --git a/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc b/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc index cc5f7e172ec9..bc5f8dd0eb68 100644 --- a/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc +++ b/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc @@ -534,6 +534,18 @@ curl -X PUT -H 'Content-type:application/json' --data-binary ' Copy-field rules have no name of their own, so v2 addresses them by their source field: the source is the final path segment, and the body carries the destinations. The v2 request attribute is `destinations`, though `dest` is accepted as an alias. ++ +[IMPORTANT] +==== +The v2 `PUT` is a replace, not an append: the destinations you send become the complete set of +copy-field rules for that source, and any rule left out is removed. +Sending the same request twice is therefore safe. + +To add a destination while keeping the existing ones, list them all, or use `add-copy-field` +through the bulk endpoint, which only ever appends. +Note that `add-copy-field` does not check for duplicates, so appending a rule that already exists +will cause the source to be copied twice. +==== === Delete a Copy Field Rule From 8510418c1da840c17d396b7d1fdcc27096627019 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20H=C3=B8ydahl?= Date: Thu, 24 Sep 2026 19:27:00 +0200 Subject: [PATCH 3/8] SOLR-18479: Complete the v2 copy-field resource Rounds out /schema/copyfields/{sourceField} so the whole resource is addressed through the path rather than partly through query parameters: GET /copyfields/{source} the source's rules PUT /copyfields/{source} set the complete destination list POST /copyfields/{source} append destinations DELETE /copyfields/{source} remove all of the source's rules DELETE /copyfields/{source}/{destinations} remove the named ones The 'destination' query parameter is gone; a trailing path segment names the destinations instead, several at a time as a comma-separated list. Splitting goes through StrUtils.splitSmart so a separator inside quotes or behind a backslash does not split; it does not trim, so surrounding whitespace (which can only arrive percent-encoded) is dropped separately. POST appends without disturbing the rules already in place, which PUT cannot do without a read-modify-write, and which therefore avoids losing one of two concurrent appends. Destinations the source already copies to are skipped rather than appended a second time, so a retried POST is harmless -- worth having for a caller that timed out without learning whether its first attempt landed. GET by source overlaps the existing source.fl query parameter on /copyfields, but reads the resource at the path the write verbs use, so the ref guide leads with it and presents source.fl as the alternative for filtering by destination or by several sources at once. --- .../SOLR-18479-v2-copyfield-api.yml | 9 +- .../client/api/endpoint/GetSchemaApi.java | 9 ++ .../client/api/endpoint/UpdateSchemaApi.java | 30 +++++-- .../handler/admin/api/GetSchemaField.java | 14 +++ .../solr/handler/admin/api/UpdateSchema.java | 66 ++++++++++++-- .../handler/admin/api/V2CopyFieldApiTest.java | 85 +++++++++++++++++-- .../api/V2UpdateSchemaErrorCaseTests.java | 2 +- .../indexing-guide/pages/schema-api.adoc | 63 ++++++++++---- 8 files changed, 235 insertions(+), 43 deletions(-) diff --git a/changelog/unreleased/SOLR-18479-v2-copyfield-api.yml b/changelog/unreleased/SOLR-18479-v2-copyfield-api.yml index 2b23c08d1ddf..7d023411888c 100644 --- a/changelog/unreleased/SOLR-18479-v2-copyfield-api.yml +++ b/changelog/unreleased/SOLR-18479-v2-copyfield-api.yml @@ -1,10 +1,11 @@ title: > - The v2 Schema API can now manage copy-field rules directly, via `PUT` and `DELETE` on + The v2 Schema API can now manage copy-field rules directly, under `/api/collections//schema/copyfields/`. Previously copy-fields were the one schema resource reachable only through the bulk endpoint. - Rules are addressed by their source field: `PUT` sets the complete `destinations` list for that - source, replacing any rules it already had, and `DELETE` removes every rule with that source - unless `destination` query parameters narrow it. + Rules are addressed by their source field: `GET` lists that source's rules, `PUT` sets its + complete `destinations` list, `POST` appends destinations without disturbing existing rules, + and `DELETE` removes them -- either all of them, or the ones named in a trailing + comma-separated path segment. type: added authors: - name: Jan Høydahl diff --git a/solr/api/src/java/org/apache/solr/client/api/endpoint/GetSchemaApi.java b/solr/api/src/java/org/apache/solr/client/api/endpoint/GetSchemaApi.java index 119bf9d19cee..d3c2b95d466a 100644 --- a/solr/api/src/java/org/apache/solr/client/api/endpoint/GetSchemaApi.java +++ b/solr/api/src/java/org/apache/solr/client/api/endpoint/GetSchemaApi.java @@ -69,6 +69,15 @@ interface Fields { tags = {"schema"}) SchemaListCopyFieldsResponse listCopyFields(); + @GET + @Path("/copyfields/{sourceField}") + @StoreApiParameters + @Operation( + summary = "List the copy-field rules copying from the specified source field", + tags = {"schema"}) + SchemaListCopyFieldsResponse listCopyFieldsBySource( + @PathParam("sourceField") String sourceField); + @GET @Path("/dynamicfields") @StoreApiParameters diff --git a/solr/api/src/java/org/apache/solr/client/api/endpoint/UpdateSchemaApi.java b/solr/api/src/java/org/apache/solr/client/api/endpoint/UpdateSchemaApi.java index 0184c3b9df36..6ce090e877e0 100644 --- a/solr/api/src/java/org/apache/solr/client/api/endpoint/UpdateSchemaApi.java +++ b/solr/api/src/java/org/apache/solr/client/api/endpoint/UpdateSchemaApi.java @@ -28,7 +28,6 @@ import jakarta.ws.rs.PUT; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; -import jakarta.ws.rs.QueryParam; import java.util.List; import org.apache.solr.client.api.model.AddCopyFieldOperation; import org.apache.solr.client.api.model.SchemaChange; @@ -129,17 +128,38 @@ SolrJerseyResponse upsertCopyFields( @PathParam("sourceField") String sourceField, @RequestBody AddCopyFieldOperation requestBody) throws Exception; + @POST + @Path("/copyfields/{sourceField}") + @StoreApiParameters + @Operation( + summary = + "Add the given destinations to the copy-field rules for the specified source field, " + + "leaving that source's existing rules in place.", + tags = {"schema"}) + SolrJerseyResponse appendCopyFields( + @PathParam("sourceField") String sourceField, @RequestBody AddCopyFieldOperation requestBody) + throws Exception; + @DELETE @Path("/copyfields/{sourceField}") @StoreApiParameters + @Operation( + summary = "Remove every copy-field rule copying from the specified source field.", + tags = {"schema"}) + SolrJerseyResponse deleteCopyFields(@PathParam("sourceField") String sourceField) + throws Exception; + + @DELETE + @Path("/copyfields/{sourceField}/{destinationFields}") + @StoreApiParameters @Operation( summary = - "Remove copy-field rules copying from the specified source field. Removes every rule " - + "with that source unless 'destination' query parameters narrow the selection.", + "Remove the copy-field rules from the specified source field to the specified " + + "destinations. Several destinations may be given as a comma-separated list.", tags = {"schema"}) - SolrJerseyResponse deleteCopyField( + SolrJerseyResponse deleteCopyFieldsByDestination( @PathParam("sourceField") String sourceField, - @QueryParam("destination") List destinations) + @PathParam("destinationFields") String destinationFields) throws Exception; @POST diff --git a/solr/core/src/java/org/apache/solr/handler/admin/api/GetSchemaField.java b/solr/core/src/java/org/apache/solr/handler/admin/api/GetSchemaField.java index 70fc868bee56..459a4e0fd316 100644 --- a/solr/core/src/java/org/apache/solr/handler/admin/api/GetSchemaField.java +++ b/solr/core/src/java/org/apache/solr/handler/admin/api/GetSchemaField.java @@ -20,6 +20,7 @@ import jakarta.inject.Inject; import java.util.List; import java.util.Map; +import java.util.Set; import org.apache.solr.api.JerseyResource; import org.apache.solr.client.api.endpoint.GetSchemaApi; import org.apache.solr.client.api.model.SchemaGetDynamicFieldInfoResponse; @@ -48,6 +49,7 @@ *

  • /fields *
  • /fields/{fieldName} *
  • /copyfields + *
  • /copyfields/{sourceField} *
  • /dynamicfields *
  • /dynamicfields/{fieldName} *
  • /fieldtypes @@ -108,6 +110,18 @@ public SchemaListCopyFieldsResponse listCopyFields() { return response; } + @Override + @PermissionName(PermissionNameProvider.Name.SCHEMA_READ_PERM) + public SchemaListCopyFieldsResponse listCopyFieldsBySource(String sourceField) { + SchemaListCopyFieldsResponse response = + instantiateJerseyResponse(SchemaListCopyFieldsResponse.class); + + response.copyFields = + List.copyOf(indexSchema.getCopyFieldProperties(false, Set.of(sourceField), null)); + + return response; + } + @Override @PermissionName(PermissionNameProvider.Name.SCHEMA_READ_PERM) public SchemaListDynamicFieldsResponse listDynamicFields() { diff --git a/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java b/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java index 3f4e09fafb22..7b55932b9f03 100644 --- a/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java +++ b/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java @@ -16,6 +16,7 @@ */ package org.apache.solr.handler.admin.api; +import static java.util.function.Predicate.not; import static org.apache.solr.common.util.CommandOperation.ERR_MSGS; import jakarta.inject.Inject; @@ -39,6 +40,7 @@ import org.apache.solr.client.api.model.UpsertFieldTypeOperation; import org.apache.solr.common.SolrErrorWrappingException; import org.apache.solr.common.SolrException; +import org.apache.solr.common.util.StrUtils; import org.apache.solr.core.SolrCore; import org.apache.solr.handler.SolrConfigHandler; import org.apache.solr.jersey.PermissionName; @@ -191,19 +193,65 @@ public SolrJerseyResponse upsertCopyFields(String sourceField, AddCopyFieldOpera @Override @PermissionName(PermissionNameProvider.Name.SCHEMA_EDIT_PERM) - public SolrJerseyResponse deleteCopyField(String sourceField, List destinations) + public SolrJerseyResponse appendCopyFields(String sourceField, AddCopyFieldOperation requestBody) throws Exception { final var response = instantiateJerseyResponse(SolrJerseyResponse.class); ensureSchemaMutable(); ensureRequiredParameterProvided("sourceField", sourceField); + ensureRequiredRequestBodyProvided(requestBody); + ensureRequiredParameterProvided("destinations", requestBody.destinations); + + // 'add-copy-field' would happily append a rule that already exists, leaving the source copied + // twice over, so skip the destinations already covered. That also makes a retried append + // harmless, which matters to a caller that timed out without learning whether its first + // attempt landed. + final var existing = Set.copyOf(currentDestinationsOf(sourceField)); + final var newDestinations = + requestBody.destinations.stream().distinct().filter(not(existing::contains)).toList(); + if (newDestinations.isEmpty()) { + return response; + } + + requestBody.source = sourceField; + requestBody.destinations = newDestinations; + requestBody.operationType = "add-copy-field"; + + runWithSchemaManager(List.of(requestBody)); + + return response; + } + + @Override + @PermissionName(PermissionNameProvider.Name.SCHEMA_EDIT_PERM) + public SolrJerseyResponse deleteCopyFields(String sourceField) throws Exception { + ensureRequiredParameterProvided("sourceField", sourceField); + return removeCopyFields(sourceField, currentDestinationsOf(sourceField)); + } + + @Override + @PermissionName(PermissionNameProvider.Name.SCHEMA_EDIT_PERM) + public SolrJerseyResponse deleteCopyFieldsByDestination( + String sourceField, String destinationFields) throws Exception { + ensureRequiredParameterProvided("sourceField", sourceField); + ensureRequiredParameterProvided("destinationFields", destinationFields); + + // Field names cannot contain a comma, so it is safe to read the segment as a list. splitSmart + // keeps separators inside quotes or behind a backslash from splitting; it does not trim, so + // surrounding whitespace is dropped here. + final var destinations = + StrUtils.splitSmart(destinationFields, ',').stream() + .map(String::trim) + .filter(not(String::isEmpty)) + .toList(); + return removeCopyFields(sourceField, destinations); + } + + private SolrJerseyResponse removeCopyFields(String sourceField, List destinations) + throws Exception { + final var response = instantiateJerseyResponse(SolrJerseyResponse.class); + ensureSchemaMutable(); - // An unqualified DELETE removes every rule with the given source; 'destination' params narrow - // that to specific rules. - final var toDelete = - (destinations == null || destinations.isEmpty()) - ? currentDestinationsOf(sourceField) - : destinations; - if (toDelete.isEmpty()) { + if (destinations.isEmpty()) { throw new SolrException( SolrException.ErrorCode.NOT_FOUND, "No copy-field rules found with source '" + sourceField + "'"); @@ -212,7 +260,7 @@ public SolrJerseyResponse deleteCopyField(String sourceField, List desti final var deleteCopyFieldOp = new DeleteCopyFieldOperation(); deleteCopyFieldOp.operationType = "delete-copy-field"; deleteCopyFieldOp.source = sourceField; - deleteCopyFieldOp.destinations = toDelete; + deleteCopyFieldOp.destinations = destinations; runWithSchemaManager(List.of(deleteCopyFieldOp)); diff --git a/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java b/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java index 37e23395022b..f111dedd2cd9 100644 --- a/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java +++ b/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java @@ -24,7 +24,6 @@ import org.apache.solr.client.solrj.request.V2Request; import org.apache.solr.cloud.SolrCloudTestCase; import org.apache.solr.common.params.MapSolrParams; -import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.util.NamedList; import org.junit.Before; import org.junit.BeforeClass; @@ -81,17 +80,33 @@ private static void putCopyFields(String source, Object payload) throws Exceptio } private static void deleteCopyFields(String source, String... destinations) throws Exception { - final var params = new ModifiableSolrParams(); - for (String destination : destinations) { - params.add("destination", destination); - } - new V2Request.Builder(schemaPath("/copyfields/" + source)) + final var suffix = destinations.length == 0 ? "" : "/" + String.join(",", destinations); + new V2Request.Builder(schemaPath("/copyfields/" + source + suffix)) .DELETE() - .withParams(params) .build() .process(cluster.getSolrClient()); } + private static void postCopyFields(String source, Object payload) throws Exception { + new V2Request.Builder(schemaPath("/copyfields/" + source)) + .POST() + .withPayload(payload) + .build() + .process(cluster.getSolrClient()); + } + + /** Destinations reported by the per-source GET endpoint. */ + @SuppressWarnings("unchecked") + private static List destinationsViaSourceEndpoint(String source) throws Exception { + final var response = + new V2Request.Builder(schemaPath("/copyfields/" + source)) + .GET() + .build() + .process(cluster.getSolrClient()); + final var copyFields = (List>) response.getResponse().get("copyFields"); + return copyFields.stream().map(rule -> (String) rule.get("dest")).sorted().toList(); + } + /** Destinations of every copy-field rule currently declared with the given source. */ @SuppressWarnings("unchecked") private static List destinationsOf(String source) throws Exception { @@ -210,6 +225,62 @@ public void testDeleteOfUnknownSourceIsNotFound() throws Exception { thrown.getMessage().contains("No copy-field rules found")); } + @Test + public void testGetBySourceReturnsOnlyThatSourcesDestinations() throws Exception { + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + + assertEquals(List.of(DEST_ONE, DEST_TWO), destinationsViaSourceEndpoint(SOURCE)); + assertEquals(List.of("id_prefix"), destinationsViaSourceEndpoint("id")); + } + + @Test + public void testGetBySourceIsEmptyForASourceWithNoRules() throws Exception { + assertEquals(List.of(), destinationsViaSourceEndpoint("no_such_source_field")); + } + + @Test + public void testPostAppendsWithoutDisturbingExistingRules() throws Exception { + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); + + postCopyFields(SOURCE, Map.of("destinations", List.of(DEST_TWO))); + + assertEquals(List.of(DEST_ONE, DEST_TWO), destinationsOf(SOURCE)); + } + + @Test + public void testPostSkipsDestinationsAlreadyPresent() throws Exception { + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); + + postCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + postCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + + // A repeated append must not leave the source copied twice over. + assertEquals(List.of(DEST_ONE, DEST_TWO), destinationsOf(SOURCE)); + } + + @Test + public void testDeleteOfSeveralDestinationsInOnePathSegment() throws Exception { + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + + deleteCopyFields(SOURCE, DEST_ONE, DEST_TWO); + + assertEquals(List.of(), destinationsOf(SOURCE)); + } + + @Test + public void testDeleteToleratesWhitespaceAroundDestinations() throws Exception { + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + + // A raw space cannot appear in a path, so whitespace only ever arrives percent-encoded. + new V2Request.Builder( + schemaPath("/copyfields/" + SOURCE + "/" + DEST_ONE + "%20,%20" + DEST_TWO)) + .DELETE() + .build() + .process(cluster.getSolrClient()); + + assertEquals(List.of(), destinationsOf(SOURCE)); + } + @Test public void testAddRequiresDestinations() throws Exception { final var thrown = diff --git a/solr/core/src/test/org/apache/solr/handler/admin/api/V2UpdateSchemaErrorCaseTests.java b/solr/core/src/test/org/apache/solr/handler/admin/api/V2UpdateSchemaErrorCaseTests.java index 490a6b65ae3e..4b5521deee20 100644 --- a/solr/core/src/test/org/apache/solr/handler/admin/api/V2UpdateSchemaErrorCaseTests.java +++ b/solr/core/src/test/org/apache/solr/handler/admin/api/V2UpdateSchemaErrorCaseTests.java @@ -188,7 +188,7 @@ public void testDeleteCopyFieldOperationRequiresSource() { expectThrows( SolrException.class, () -> { - schemaApi.deleteCopyField(null, List.of("someDestination")); + schemaApi.deleteCopyFields(null); }); assertEquals(BAD_REQUEST.code, thrown.code()); assertThat(thrown.getMessage(), containsString("Missing required parameter: sourceField")); diff --git a/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc b/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc index bc5f8dd0eb68..aa15a85efb21 100644 --- a/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc +++ b/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc @@ -490,6 +490,7 @@ s|Required |Default: none |=== + A field or an array of fields to which the source field will be copied. +In the v2 API this attribute is named `destinations`; `dest` is still accepted as an alias. `maxChars`:: + @@ -537,15 +538,24 @@ The v2 request attribute is `destinations`, though `dest` is accepted as an alia + [IMPORTANT] ==== -The v2 `PUT` is a replace, not an append: the destinations you send become the complete set of -copy-field rules for that source, and any rule left out is removed. +`PUT` is a replace, not an append: the destinations you send become the complete set of copy-field +rules for that source, and any rule left out is removed. Sending the same request twice is therefore safe. - -To add a destination while keeping the existing ones, list them all, or use `add-copy-field` -through the bulk endpoint, which only ever appends. -Note that `add-copy-field` does not check for duplicates, so appending a rule that already exists -will cause the source to be copied twice. ==== ++ +To add destinations while leaving the source's existing rules alone, `POST` to the same path: ++ +[source,bash] +---- +curl -X POST -H 'Content-type:application/json' --data-binary ' +{ + "destinations":[ "catchall" ] +}' http://localhost:8983/api/collections/techproducts/schema/copyfields/shelf +---- ++ +Destinations that the source already copies to are ignored, so a repeated `POST` will not leave the +source copied twice over. +The `add-copy-field` command available through the bulk endpoint performs no such check. === Delete a Copy Field Rule @@ -574,13 +584,20 @@ V2 API:: ==== [source,bash] ---- -curl -X DELETE "http://localhost:8983/api/collections/techproducts/schema/copyfields/shelf?destination=location" +curl -X DELETE "http://localhost:8983/api/collections/techproducts/schema/copyfields/shelf/location" ---- ==== ====== + -Repeat the `destination` parameter to remove several rules at once. -Omitting it entirely removes *every* rule with that source. +Several destinations may be removed at once by giving them as a comma-separated list, and omitting +the destinations entirely removes *every* rule with that source: ++ +[source,bash] +---- +curl -X DELETE "http://localhost:8983/api/collections/techproducts/schema/copyfields/shelf/location,catchall" +curl -X DELETE "http://localhost:8983/api/collections/techproducts/schema/copyfields/shelf" +---- ++ Deleting a source that has no copy-field rules returns a 404. === Multiple Commands in a Single POST @@ -653,7 +670,8 @@ curl -X POST -H 'Content-type:application/json' --data-binary '{ }' http://localhost:8983/solr/techproducts/schema ---- -Bulk schema operations are also supported in Solr's v2 API, using a slightly different syntax. +Bulk schema operations are also supported in Solr's v2 API, using a different endpoint and syntax. +The v2 bulk endpoint is `POST /api/collections/_collection_/schema/bulk`; the `/schema` path itself only supports `GET` in v2. Individual operations are specified as elements within a list, with the operation name (e.g. `add-field`, `delete-field-type`) specified as a `"operationType"` property on each operation object: [source,bash] @@ -661,23 +679,23 @@ Individual operations are specified as elements within a list, with the operatio curl -X POST -H 'Content-type:application/json' --data-binary ' [ { - "operationType": "add-field" + "operationType": "add-field", "name": "shelf", "type": "myNewTxtField", - "stored": true + "stored": true }, { - "operationType": "add-field" + "operationType": "add-field", "name": "location", "type": "myNewTxtField", - "stored": true + "stored": true }, { - "operationType": "add-copy-field" + "operationType": "add-copy-field", "source": "shelf", "destinations": ["location", "catchall"] } - ]' http://localhost:8983/solr/techproducts/schema/bulk + ]' http://localhost:8983/api/collections/techproducts/schema/bulk ---- === Schema Changes Among Replicas @@ -1287,6 +1305,17 @@ The sample output below has been truncated to show a few different field types f `GET /_collection_/schema/copyfields` +To list the rules for a single source field, prefer the v2 path form, which reads the same resource +that the `PUT`, `POST` and `DELETE` operations above address: + +[source,bash] +---- +curl -X GET "http://localhost:8983/api/collections/techproducts/schema/copyfields/shelf" +---- + +The `source.fl` query parameter described below is an alternative, and is the only option when +filtering by destination or by more than one source at a time. + ==== List Copy Field Parameters *Path Parameters* From 2b43853e2280a07ab535c9344fbd4c926e6e9fcb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20H=C3=B8ydahl?= Date: Thu, 24 Sep 2026 19:49:09 +0200 Subject: [PATCH 4/8] SOLR-18479: Diff copy-field rules under the schema update lock The replace and append operations worked out which rules to remove or skip in the resource method, before handing SchemaManager a fixed list of operations. That read happens outside the schema update lock, while doOperations takes the lock, refreshes the schema and replays the operations on every retry. The list could therefore be stale precisely when it mattered: a concurrently added destination survived a replace, and a retry triggered by another node's change could fail with "Copy field directive not found" for a rule that had since been removed. Move the diffing into two internal-only operations, upsert-copy-field and append-copy-field, alongside the existing internal upsert-field. They inspect managedIndexSchema, which doOperations refreshes under the lock, so each attempt diffs against the rules actually in effect. Append builds a fresh operation rather than narrowing the caller's, so a retry does not inherit the previous attempt's filtering. Deleting every rule for a source now goes through the same path, by replacing its rules with none; the remaining out-of-lock read is only to report 404 for a source that has no rules at all. Also from review: - A path segment naming no destinations, e.g. /copyfields/src/,,, answered 404 claiming the source had no rules, when the request was simply malformed and the source may well have rules. It is now a 400. - A request body whose 'source' contradicts the path was silently overwritten; it is now rejected. - Documented that a PUT with an empty destinations list clears the source, and that a GET for a source with no rules returns an empty list rather than 404. The test setup uses the former to reset state, which no longer needs to swallow a 404. --- .../solr/handler/admin/api/UpdateSchema.java | 108 +++++++++--------- .../org/apache/solr/schema/SchemaManager.java | 63 ++++++++++ .../handler/admin/api/V2CopyFieldApiTest.java | 54 ++++++--- .../indexing-guide/pages/schema-api.adoc | 2 + 4 files changed, 155 insertions(+), 72 deletions(-) diff --git a/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java b/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java index 7b55932b9f03..18a1d7e37c9b 100644 --- a/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java +++ b/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java @@ -20,7 +20,7 @@ import static org.apache.solr.common.util.CommandOperation.ERR_MSGS; import jakarta.inject.Inject; -import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; @@ -40,7 +40,6 @@ import org.apache.solr.client.api.model.UpsertFieldTypeOperation; import org.apache.solr.common.SolrErrorWrappingException; import org.apache.solr.common.SolrException; -import org.apache.solr.common.util.StrUtils; import org.apache.solr.core.SolrCore; import org.apache.solr.handler.SolrConfigHandler; import org.apache.solr.jersey.PermissionName; @@ -162,59 +161,34 @@ public SolrJerseyResponse deleteFieldType(String fieldTypeName) throws Exception @PermissionName(PermissionNameProvider.Name.SCHEMA_EDIT_PERM) public SolrJerseyResponse upsertCopyFields(String sourceField, AddCopyFieldOperation requestBody) throws Exception { - final var response = instantiateJerseyResponse(SolrJerseyResponse.class); - ensureSchemaMutable(); - ensureRequiredParameterProvided("sourceField", sourceField); - ensureRequiredRequestBodyProvided(requestBody); - ensureRequiredParameterProvided("destinations", requestBody.destinations); - requestBody.source = sourceField; - requestBody.operationType = "add-copy-field"; - - // 'add-copy-field' is purely additive: it appends a rule without checking whether an identical - // one is already present, so repeating it would silently copy the source twice over. Clearing - // the source's existing rules first is what makes this PUT idempotent, and lets the body state - // the rules the caller wants rather than only the ones being added. - final var operations = new ArrayList(); - final var existing = currentDestinationsOf(sourceField); - if (!existing.isEmpty()) { - final var replacedOp = new DeleteCopyFieldOperation(); - replacedOp.operationType = "delete-copy-field"; - replacedOp.source = sourceField; - replacedOp.destinations = existing; - operations.add(replacedOp); - } - operations.add(requestBody); - - // SchemaManager applies the list as a unit, so a failure to add leaves the old rules in place. - runWithSchemaManager(operations); - - return response; + return runCopyFieldOperation(sourceField, requestBody, "upsert-copy-field"); } @Override @PermissionName(PermissionNameProvider.Name.SCHEMA_EDIT_PERM) public SolrJerseyResponse appendCopyFields(String sourceField, AddCopyFieldOperation requestBody) throws Exception { + return runCopyFieldOperation(sourceField, requestBody, "append-copy-field"); + } + + /** + * Runs one of the copy-field operations that diff against the current schema. + * + *

    Both leave the diffing to {@link SchemaManager}, which performs it against a schema + * refreshed under the update lock; doing it here would go stale whenever SchemaManager retries. + */ + private SolrJerseyResponse runCopyFieldOperation( + String sourceField, AddCopyFieldOperation requestBody, String operationType) + throws Exception { final var response = instantiateJerseyResponse(SolrJerseyResponse.class); ensureSchemaMutable(); ensureRequiredParameterProvided("sourceField", sourceField); ensureRequiredRequestBodyProvided(requestBody); ensureRequiredParameterProvided("destinations", requestBody.destinations); - - // 'add-copy-field' would happily append a rule that already exists, leaving the source copied - // twice over, so skip the destinations already covered. That also makes a retried append - // harmless, which matters to a caller that timed out without learning whether its first - // attempt landed. - final var existing = Set.copyOf(currentDestinationsOf(sourceField)); - final var newDestinations = - requestBody.destinations.stream().distinct().filter(not(existing::contains)).toList(); - if (newDestinations.isEmpty()) { - return response; - } + ensureBodySourceAgreesWithPath(sourceField, requestBody.source); requestBody.source = sourceField; - requestBody.destinations = newDestinations; - requestBody.operationType = "add-copy-field"; + requestBody.operationType = operationType; runWithSchemaManager(List.of(requestBody)); @@ -224,38 +198,45 @@ public SolrJerseyResponse appendCopyFields(String sourceField, AddCopyFieldOpera @Override @PermissionName(PermissionNameProvider.Name.SCHEMA_EDIT_PERM) public SolrJerseyResponse deleteCopyFields(String sourceField) throws Exception { + ensureSchemaMutable(); ensureRequiredParameterProvided("sourceField", sourceField); - return removeCopyFields(sourceField, currentDestinationsOf(sourceField)); + + // Only to report a missing resource; the deletion itself re-reads under the schema update + // lock, so a rule added in the meantime is still removed. + if (currentDestinationsOf(sourceField).isEmpty()) { + throw new SolrException( + SolrException.ErrorCode.NOT_FOUND, + "No copy-field rules found with source '" + sourceField + "'"); + } + + // Replacing the source's rules with none removes all of them. + final var clearOp = new AddCopyFieldOperation(); + clearOp.destinations = List.of(); + return runCopyFieldOperation(sourceField, clearOp, "upsert-copy-field"); } @Override @PermissionName(PermissionNameProvider.Name.SCHEMA_EDIT_PERM) public SolrJerseyResponse deleteCopyFieldsByDestination( String sourceField, String destinationFields) throws Exception { + ensureSchemaMutable(); ensureRequiredParameterProvided("sourceField", sourceField); ensureRequiredParameterProvided("destinationFields", destinationFields); - // Field names cannot contain a comma, so it is safe to read the segment as a list. splitSmart - // keeps separators inside quotes or behind a backslash from splitting; it does not trim, so - // surrounding whitespace is dropped here. + // Field names cannot contain a comma, so it is safe to read the segment as a list. final var destinations = - StrUtils.splitSmart(destinationFields, ',').stream() - .map(String::trim) - .filter(not(String::isEmpty)) - .toList(); + Arrays.stream(destinationFields.split(",")).filter(not(String::isEmpty)).toList(); + if (destinations.isEmpty()) { + throw new SolrException( + SolrException.ErrorCode.BAD_REQUEST, + "No destinations given in '" + destinationFields + "'"); + } return removeCopyFields(sourceField, destinations); } private SolrJerseyResponse removeCopyFields(String sourceField, List destinations) throws Exception { final var response = instantiateJerseyResponse(SolrJerseyResponse.class); - ensureSchemaMutable(); - - if (destinations.isEmpty()) { - throw new SolrException( - SolrException.ErrorCode.NOT_FOUND, - "No copy-field rules found with source '" + sourceField + "'"); - } final var deleteCopyFieldOp = new DeleteCopyFieldOperation(); deleteCopyFieldOp.operationType = "delete-copy-field"; @@ -267,6 +248,19 @@ private SolrJerseyResponse removeCopyFields(String sourceField, List des return response; } + /** Rejects a request body whose 'source' contradicts the source named in the path. */ + private void ensureBodySourceAgreesWithPath(String sourceField, String bodySource) { + if (bodySource != null && !bodySource.equals(sourceField)) { + throw new SolrException( + SolrException.ErrorCode.BAD_REQUEST, + "Request body source '" + + bodySource + + "' does not match the source in the path, '" + + sourceField + + "'"); + } + } + /** * Lists the destinations of every copy-field rule currently declared with the given source. * diff --git a/solr/core/src/java/org/apache/solr/schema/SchemaManager.java b/solr/core/src/java/org/apache/solr/schema/SchemaManager.java index 131e701199ea..62dc71ca95f4 100644 --- a/solr/core/src/java/org/apache/solr/schema/SchemaManager.java +++ b/solr/core/src/java/org/apache/solr/schema/SchemaManager.java @@ -226,6 +226,26 @@ public SchemaOperationException(String message) { } } + /** + * Destinations of the copy-field rules that the in-progress schema declares for the given source. + * + *

    Covers dynamic (i.e. glob) rules as well as explicit ones. + */ + private List destinationsOf(String source) { + return managedIndexSchema.getCopyFieldProperties(false, Set.of(source), null).stream() + .map(properties -> (String) properties.get(IndexSchema.DESTINATION)) + .toList(); + } + + private static DeleteCopyFieldOperation deleteCopyFieldOp( + String source, List destinations) { + final var op = new DeleteCopyFieldOperation(); + op.operationType = "delete-copy-field"; + op.source = source; + op.destinations = destinations; + return op; + } + private static T ensureNotNull(String name, T value) throws SchemaOperationException { if (value == null) { throw new SchemaOperationException("'" + name + "' is a required field"); @@ -275,6 +295,49 @@ public boolean perform(SchemaChange op, SchemaManager mgr) throws SchemaOperatio } } }, + UPSERT_COPY_FIELD("upsert-copy-field") { // Internal only, to support v2 API + @Override + public boolean perform(SchemaChange op, SchemaManager mgr) throws SchemaOperationException { + final var upsertOp = (AddCopyFieldOperation) op; + String source = ensureNotNull("source", upsertOp.source); + ensureNotNull("dest", upsertOp.destinations); + + // Runs against mgr.managedIndexSchema, which doOperations refreshes under the schema + // update lock, so the rules being replaced are the ones actually in effect. Computing + // this outside would go stale whenever doOperations retries. + final var existing = mgr.destinationsOf(source); + if (!existing.isEmpty()) { + DELETE_COPY_FIELD.perform(deleteCopyFieldOp(source, existing), mgr); + } + return ADD_COPY_FIELD.perform(op, mgr); + } + }, + APPEND_COPY_FIELD("append-copy-field") { // Internal only, to support v2 API + @Override + public boolean perform(SchemaChange op, SchemaManager mgr) throws SchemaOperationException { + final var appendOp = (AddCopyFieldOperation) op; + String source = ensureNotNull("source", appendOp.source); + List dests = ensureNotNull("dest", appendOp.destinations); + + // 'add-copy-field' does not check for duplicates, so a destination the source already + // copies to would be registered twice and copied twice at index time. + final var existing = Set.copyOf(mgr.destinationsOf(source)); + final var toAdd = + dests.stream().distinct().filter(dest -> !existing.contains(dest)).toList(); + if (toAdd.isEmpty()) { + return true; + } + + // A fresh op rather than mutating the caller's: doOperations replays the same op objects + // when it retries, and a narrowed list must not leak into the next attempt. + final var addOp = new AddCopyFieldOperation(); + addOp.operationType = "add-copy-field"; + addOp.source = source; + addOp.destinations = toAdd; + addOp.maxChars = appendOp.maxChars; + return ADD_COPY_FIELD.perform(addOp, mgr); + } + }, UPSERT_FIELD("upsert-field") { // Internal only @Override public boolean perform(SchemaChange op, SchemaManager mgr) throws SchemaOperationException { diff --git a/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java b/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java index f111dedd2cd9..7dd0eda11acb 100644 --- a/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java +++ b/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java @@ -57,14 +57,9 @@ public static void setupCluster() throws Exception { @Before public void clearCopyFields() throws Exception { - // Leave each test a clean slate; the source may legitimately have no rules yet. - try { - deleteCopyFields(SOURCE); - } catch (RemoteSolrException e) { - if (e.code() != 404) { - throw e; - } - } + // A replace with no destinations clears the source whether or not it currently has rules, + // so unlike DELETE this needs no special case for the empty state. + putCopyFields(SOURCE, Map.of("destinations", List.of())); } private static String schemaPath(String suffix) { @@ -268,19 +263,48 @@ public void testDeleteOfSeveralDestinationsInOnePathSegment() throws Exception { } @Test - public void testDeleteToleratesWhitespaceAroundDestinations() throws Exception { + public void testPutWithNoDestinationsClearsTheSource() throws Exception { putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); - // A raw space cannot appear in a path, so whitespace only ever arrives percent-encoded. - new V2Request.Builder( - schemaPath("/copyfields/" + SOURCE + "/" + DEST_ONE + "%20,%20" + DEST_TWO)) - .DELETE() - .build() - .process(cluster.getSolrClient()); + putCopyFields(SOURCE, Map.of("destinations", List.of())); assertEquals(List.of(), destinationsOf(SOURCE)); } + @Test + public void testDeleteRejectsAPathSegmentNamingNoDestinations() throws Exception { + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); + + final var thrown = + expectThrows( + RemoteSolrException.class, + () -> + new V2Request.Builder(schemaPath("/copyfields/" + SOURCE + "/,,,")) + .DELETE() + .build() + .process(cluster.getSolrClient())); + + // The source does have rules, so this is a malformed request rather than a missing resource. + assertEquals(400, thrown.code()); + assertEquals(List.of(DEST_ONE), destinationsOf(SOURCE)); + } + + @Test + public void testBodySourceContradictingThePathIsRejected() { + final var thrown = + expectThrows( + RemoteSolrException.class, + () -> + putCopyFields( + SOURCE, + Map.of("source", "some_other_source", "destinations", List.of(DEST_ONE)))); + + assertEquals(400, thrown.code()); + assertTrue( + "unexpected message: " + thrown.getMessage(), + thrown.getMessage().contains("does not match the source in the path")); + } + @Test public void testAddRequiresDestinations() throws Exception { final var thrown = diff --git a/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc b/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc index aa15a85efb21..f701d1239aa4 100644 --- a/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc +++ b/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc @@ -541,6 +541,7 @@ The v2 request attribute is `destinations`, though `dest` is accepted as an alia `PUT` is a replace, not an append: the destinations you send become the complete set of copy-field rules for that source, and any rule left out is removed. Sending the same request twice is therefore safe. +Sending an empty `destinations` list removes every rule with that source. ==== + To add destinations while leaving the source's existing rules alone, `POST` to the same path: @@ -1315,6 +1316,7 @@ curl -X GET "http://localhost:8983/api/collections/techproducts/schema/copyfield The `source.fl` query parameter described below is an alternative, and is the only option when filtering by destination or by more than one source at a time. +A source with no copy-field rules returns an empty list rather than a 404. ==== List Copy Field Parameters From 67fb81a850dc85bbe3079604e36923cf8321155e Mon Sep 17 00:00:00 2001 From: Eric Pugh Date: Sun, 22 Nov 2026 07:38:53 -0500 Subject: [PATCH 5/8] SOLR-18479: Fix copy-field client bodies and missing-rule errors --- .../client/api/endpoint/UpdateSchemaApi.java | 6 +- .../solr/handler/admin/api/UpdateSchema.java | 2 +- .../solr/schema/ManagedIndexSchema.java | 14 ++- .../org/apache/solr/schema/SchemaManager.java | 38 ++++-- .../handler/admin/api/V2CopyFieldApiTest.java | 115 ++++++++++++++++++ .../indexing-guide/pages/schema-api.adoc | 2 +- 6 files changed, 159 insertions(+), 18 deletions(-) diff --git a/solr/api/src/java/org/apache/solr/client/api/endpoint/UpdateSchemaApi.java b/solr/api/src/java/org/apache/solr/client/api/endpoint/UpdateSchemaApi.java index 6ce090e877e0..6abb947cbbec 100644 --- a/solr/api/src/java/org/apache/solr/client/api/endpoint/UpdateSchemaApi.java +++ b/solr/api/src/java/org/apache/solr/client/api/endpoint/UpdateSchemaApi.java @@ -125,7 +125,8 @@ SolrJerseyResponse deleteFieldType(@PathParam("fieldTypeName") String fieldTypeN + "replace any rules that source already has.", tags = {"schema"}) SolrJerseyResponse upsertCopyFields( - @PathParam("sourceField") String sourceField, @RequestBody AddCopyFieldOperation requestBody) + @PathParam("sourceField") String sourceField, + @RequestBody(required = true) AddCopyFieldOperation requestBody) throws Exception; @POST @@ -137,7 +138,8 @@ SolrJerseyResponse upsertCopyFields( + "leaving that source's existing rules in place.", tags = {"schema"}) SolrJerseyResponse appendCopyFields( - @PathParam("sourceField") String sourceField, @RequestBody AddCopyFieldOperation requestBody) + @PathParam("sourceField") String sourceField, + @RequestBody(required = true) AddCopyFieldOperation requestBody) throws Exception; @DELETE diff --git a/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java b/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java index 18a1d7e37c9b..5ac20e491340 100644 --- a/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java +++ b/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java @@ -239,7 +239,7 @@ private SolrJerseyResponse removeCopyFields(String sourceField, List des final var response = instantiateJerseyResponse(SolrJerseyResponse.class); final var deleteCopyFieldOp = new DeleteCopyFieldOperation(); - deleteCopyFieldOp.operationType = "delete-copy-field"; + deleteCopyFieldOp.operationType = "delete-copy-field-by-destination"; deleteCopyFieldOp.source = sourceField; deleteCopyFieldOp.destinations = destinations; diff --git a/solr/core/src/java/org/apache/solr/schema/ManagedIndexSchema.java b/solr/core/src/java/org/apache/solr/schema/ManagedIndexSchema.java index e1be86a3d05e..5de458e71540 100644 --- a/solr/core/src/java/org/apache/solr/schema/ManagedIndexSchema.java +++ b/solr/core/src/java/org/apache/solr/schema/ManagedIndexSchema.java @@ -892,8 +892,14 @@ public ManagedIndexSchema addCopyFields( } @Override - @SuppressWarnings({"unchecked"}) public ManagedIndexSchema deleteCopyFields(Map> copyFields) { + return deleteCopyFields(copyFields, ErrorCode.BAD_REQUEST); + } + + /** Deletes copy-field rules, using the supplied error code when a rule is absent. */ + @SuppressWarnings({"unchecked"}) + public ManagedIndexSchema deleteCopyFields( + Map> copyFields, ErrorCode missingRuleErrorCode) { ManagedIndexSchema newSchema; if (isMutable) { newSchema = shallowCopy(true); @@ -909,7 +915,7 @@ public ManagedIndexSchema deleteCopyFields(Map> copyF for (Map.Entry> entry : copyFields.entrySet()) { // Key is the source, values are the destinations for (String destination : entry.getValue()) { - newSchema.deleteCopyField(entry.getKey(), destination); + newSchema.deleteCopyField(entry.getKey(), destination, missingRuleErrorCode); } } newSchema.postReadInform(); @@ -922,7 +928,7 @@ public ManagedIndexSchema deleteCopyFields(Map> copyF return newSchema; } - private void deleteCopyField(String source, String dest) { + private void deleteCopyField(String source, String dest, ErrorCode missingRuleErrorCode) { // Assumption: a copy field directive will exist only if the source & destination (dynamic) // fields exist SchemaField destSchemaField = fields.get(dest); @@ -986,7 +992,7 @@ private void deleteCopyField(String source, String dest) { } if (!found) { throw new SolrException( - ErrorCode.BAD_REQUEST, + missingRuleErrorCode, "Copy field directive not found: '" + source + "' -> '" + dest + "'"); } } diff --git a/solr/core/src/java/org/apache/solr/schema/SchemaManager.java b/solr/core/src/java/org/apache/solr/schema/SchemaManager.java index d2e006a10eb8..4368f163b2f4 100644 --- a/solr/core/src/java/org/apache/solr/schema/SchemaManager.java +++ b/solr/core/src/java/org/apache/solr/schema/SchemaManager.java @@ -316,6 +316,25 @@ private static DeleteCopyFieldOperation deleteCopyFieldOp( return op; } + private boolean deleteCopyFields( + DeleteCopyFieldOperation operation, SolrException.ErrorCode missingRuleErrorCode) + throws SchemaOperationException { + String source = ensureNotNull("source", operation.source); + List destinations = ensureNotNull("dest", operation.destinations); + try { + managedIndexSchema = + managedIndexSchema.deleteCopyFields(Map.of(source, destinations), missingRuleErrorCode); + return true; + } catch (Exception e) { + if (e instanceof SolrException exception + && exception.code() == SolrException.ErrorCode.NOT_FOUND.code) { + throw exception; + } + log.error("Could not delete copy field", e); + throw new SchemaOperationException(getErrorStr(e)); + } + } + private static T ensureNotNull(String name, T value) throws SchemaOperationException { if (value == null) { throw new SchemaOperationException("'" + name + "' is a required field"); @@ -495,16 +514,15 @@ public boolean perform(SchemaChange op, SchemaManager mgr) throws SchemaOperatio DELETE_COPY_FIELD("delete-copy-field") { @Override public boolean perform(SchemaChange op, SchemaManager mgr) throws SchemaOperationException { - final var deleteCopyField = (DeleteCopyFieldOperation) op; - String source = ensureNotNull("source", deleteCopyField.source); - List dests = ensureNotNull("dest", deleteCopyField.destinations); - try { - mgr.managedIndexSchema = mgr.managedIndexSchema.deleteCopyFields(Map.of(source, dests)); - return true; - } catch (Exception e) { - log.error("Could not delete copy field", e); - throw new SchemaOperationException(getErrorStr(e)); - } + return mgr.deleteCopyFields( + (DeleteCopyFieldOperation) op, SolrException.ErrorCode.BAD_REQUEST); + } + }, + DELETE_COPY_FIELD_BY_DESTINATION("delete-copy-field-by-destination") { + @Override + public boolean perform(SchemaChange op, SchemaManager mgr) throws SchemaOperationException { + return mgr.deleteCopyFields( + (DeleteCopyFieldOperation) op, SolrException.ErrorCode.NOT_FOUND); } }, DELETE_FIELD("delete-field") { diff --git a/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java b/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java index 7dd0eda11acb..12fb68730488 100644 --- a/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java +++ b/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java @@ -19,9 +19,12 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import org.apache.solr.client.api.model.IndexType; import org.apache.solr.client.solrj.RemoteSolrException; import org.apache.solr.client.solrj.request.CollectionAdminRequest; +import org.apache.solr.client.solrj.request.SchemaApi; import org.apache.solr.client.solrj.request.V2Request; +import org.apache.solr.client.solrj.request.schema.SchemaRequest; import org.apache.solr.cloud.SolrCloudTestCase; import org.apache.solr.common.params.MapSolrParams; import org.apache.solr.common.util.NamedList; @@ -126,6 +129,41 @@ public void testAddAndListCopyFieldsBySource() throws Exception { assertEquals(List.of(DEST_ONE, DEST_TWO), destinationsOf(SOURCE)); } + @Test + public void testGeneratedPutReplacesCopyFields() throws Exception { + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + + var request = new SchemaApi.UpsertCopyFields(IndexType.COLLECTION, COLLECTION, SOURCE); + request.setDestinations(List.of(DEST_TWO)); + request.setMaxChars(100); + assertEquals(0, request.process(cluster.getSolrClient()).responseHeader.status); + + var response = + new SchemaApi.ListCopyFieldsBySource(IndexType.COLLECTION, COLLECTION, SOURCE) + .process(cluster.getSolrClient()); + assertEquals( + List.of(Map.of("source", SOURCE, "dest", DEST_TWO, "maxChars", 100)), response.copyFields); + } + + @Test + public void testGeneratedPostAppendsCopyFields() throws Exception { + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); + + var request = new SchemaApi.AppendCopyFields(IndexType.COLLECTION, COLLECTION, SOURCE); + request.setDestinations(List.of(DEST_TWO)); + request.setMaxChars(100); + assertEquals(0, request.process(cluster.getSolrClient()).responseHeader.status); + + var response = + new SchemaApi.ListCopyFieldsBySource(IndexType.COLLECTION, COLLECTION, SOURCE) + .process(cluster.getSolrClient()); + assertEquals( + List.of( + Map.of("source", SOURCE, "dest", DEST_ONE), + Map.of("source", SOURCE, "dest", DEST_TWO, "maxChars", 100)), + response.copyFields); + } + @Test public void testRepeatedPutIsIdempotent() throws Exception { putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); @@ -262,6 +300,83 @@ public void testDeleteOfSeveralDestinationsInOnePathSegment() throws Exception { assertEquals(List.of(), destinationsOf(SOURCE)); } + @Test + public void testDeleteOfMissingNamedRuleIsNotFound() throws Exception { + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); + + var thrown = expectThrows(RemoteSolrException.class, () -> deleteCopyFields(SOURCE, DEST_TWO)); + + assertEquals(404, thrown.code()); + assertTrue(thrown.getMessage(), thrown.getMessage().contains("Copy field directive not found")); + assertEquals(List.of(DEST_ONE), destinationsOf(SOURCE)); + } + + @Test + public void testDeleteOfNamedRuleWithUnknownSourceIsNotFound() throws Exception { + var thrown = + expectThrows( + RemoteSolrException.class, () -> deleteCopyFields("no_such_source_field", DEST_ONE)); + + assertEquals(404, thrown.code()); + } + + @Test + public void testDeleteOfMissingNamedRuleLeavesOtherRulesIntact() throws Exception { + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); + + var thrown = + expectThrows(RemoteSolrException.class, () -> deleteCopyFields(SOURCE, DEST_ONE, DEST_TWO)); + + assertEquals(404, thrown.code()); + assertEquals(List.of(DEST_ONE), destinationsOf(SOURCE)); + } + + @Test + public void testDeleteOfInvalidDestinationGlobIsBadRequest() throws Exception { + putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); + + var thrown = + expectThrows(RemoteSolrException.class, () -> deleteCopyFields(SOURCE, "invalid**glob")); + + assertEquals(400, thrown.code()); + assertEquals(List.of(DEST_ONE), destinationsOf(SOURCE)); + } + + @Test + public void testBulkDeleteOfMissingRuleIsBadRequest() throws Exception { + var thrown = + expectThrows( + RemoteSolrException.class, + () -> + new V2Request.Builder(schemaPath("/bulk")) + .POST() + .withPayload( + List.of( + Map.of( + "operationType", + "delete-copy-field", + "source", + SOURCE, + "destinations", + List.of(DEST_TWO)))) + .build() + .process(cluster.getSolrClient())); + + assertEquals(400, thrown.code()); + } + + @Test + public void testV1DeleteOfMissingRuleIsBadRequest() { + var thrown = + expectThrows( + RemoteSolrException.class, + () -> + new SchemaRequest.DeleteCopyField(SOURCE, List.of(DEST_TWO)) + .process(cluster.getSolrClient(), COLLECTION)); + + assertEquals(400, thrown.code()); + } + @Test public void testPutWithNoDestinationsClearsTheSource() throws Exception { putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); diff --git a/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc b/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc index 3502f8c8833f..f04c83843300 100644 --- a/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc +++ b/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc @@ -604,7 +604,7 @@ curl -X DELETE "http://localhost:8983/api/collections/techproducts/schema/copyfi curl -X DELETE "http://localhost:8983/api/collections/techproducts/schema/copyfields/shelf" ---- + -Deleting a source that has no copy-field rules returns a 404. +Deleting a source that has no copy-field rules, or naming a rule that does not exist, returns a 404. === Multiple Commands in a Single POST From 8f471a3e4756af12246798576ed8a33b995e4310 Mon Sep 17 00:00:00 2001 From: Eric Pugh Date: Sun, 22 Nov 2026 08:30:42 -0500 Subject: [PATCH 6/8] Use the API "in anger" in the Admin UI! --- .../SOLR-18479-v2-copyfield-api.yml | 2 + .../solr/webapp/AdminUiSchemaScreenTest.java | 108 +++++++++++++++++- .../web/js/angular/controllers/schema.js | 20 ++-- 3 files changed, 116 insertions(+), 14 deletions(-) diff --git a/changelog/unreleased/SOLR-18479-v2-copyfield-api.yml b/changelog/unreleased/SOLR-18479-v2-copyfield-api.yml index 7d023411888c..30cfc02de6dd 100644 --- a/changelog/unreleased/SOLR-18479-v2-copyfield-api.yml +++ b/changelog/unreleased/SOLR-18479-v2-copyfield-api.yml @@ -6,9 +6,11 @@ title: > complete `destinations` list, `POST` appends destinations without disturbing existing rules, and `DELETE` removes them -- either all of them, or the ones named in a trailing comma-separated path segment. + The Admin UI uses these endpoints to add and delete copy-field rules. type: added authors: - name: Jan Høydahl + - name: Eric Pugh links: - name: SOLR-18479 url: https://issues.apache.org/jira/browse/SOLR-18479 diff --git a/solr/webapp/src/test/org/apache/solr/webapp/AdminUiSchemaScreenTest.java b/solr/webapp/src/test/org/apache/solr/webapp/AdminUiSchemaScreenTest.java index 372a38bdd336..800d16d3b9c0 100644 --- a/solr/webapp/src/test/org/apache/solr/webapp/AdminUiSchemaScreenTest.java +++ b/solr/webapp/src/test/org/apache/solr/webapp/AdminUiSchemaScreenTest.java @@ -19,20 +19,25 @@ import java.util.List; import java.util.Map; import org.apache.solr.client.solrj.SolrClient; +import org.apache.solr.client.solrj.request.schema.SchemaRequest; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.util.NamedList; import org.junit.BeforeClass; import org.junit.Test; import org.openqa.selenium.By; +import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebElement; /** * Tests the Schema Browser screen: browsing fields and their flags, term info, and adding/deleting - * a field through the UI dialogs (the fixture uses a mutable managed schema). + * fields and copy-field rules through the UI dialogs (the fixture uses a mutable managed schema). */ public class AdminUiSchemaScreenTest extends AdminUiTestBase { private static final String COLLECTION = "schemacoll"; + private static final String COPY_SOURCE = "ui_copy_source"; + private static final String COPY_DEST_ONE = "ui_copy_dest_one"; + private static final String COPY_DEST_TWO = "ui_copy_dest_two"; @BeforeClass public static void setupCollection() throws Exception { @@ -44,6 +49,10 @@ public static void setupCollection() throws Exception { client.add(doc); } client.commit(); + for (String field : List.of(COPY_SOURCE, COPY_DEST_ONE, COPY_DEST_TWO)) { + new SchemaRequest.AddField(Map.of("name", field, "type", "string", "multiValued", true)) + .process(cluster.getSolrClient(), COLLECTION); + } } @Test @@ -101,6 +110,103 @@ public void testAddAndDeleteFieldViaUi() throws Exception { assertNoSevereConsoleErrors(); } + @Test + public void testCopyFieldsUseDedicatedEndpoints() throws Exception { + new SchemaRequest.AddCopyField(COPY_SOURCE, List.of(COPY_DEST_ONE)) + .process(cluster.getSolrClient(), COLLECTION); + try { + openPage(COLLECTION + "/schema", By.id("schema")); + openAddCopyFieldDialog(); + waitFor(By.id("add_source")).sendKeys(COPY_SOURCE); + waitFor(By.id("add_dest")).sendKeys(COPY_DEST_TWO); + ((JavascriptExecutor) driver).executeScript("performance.clearResourceTimings();"); + click(By.xpath("//button[@ng-click='addCopyField()']")); + + waitUntil( + "adding a copy rule should retain the source's existing destinations", + () -> copyFieldDestinations().equals(List.of(COPY_DEST_ONE, COPY_DEST_TWO))); + String copyFieldPath = "/api/collections/" + COLLECTION + "/schema/copyfields/" + COPY_SOURCE; + assertBrowserRequested(copyFieldPath); + + openPage(COLLECTION + "/schema?field=" + COPY_SOURCE, By.id("schema")); + waitForTextContains(By.cssSelector("#schema span.name"), COPY_SOURCE); + String destinationRow = + "//dd[contains(@class,'copyfield')][.//a[normalize-space()='" + COPY_DEST_TWO + "']]"; + click(By.xpath(destinationRow + "//span[@ng-click='toggleDeleteCopyField(field)']")); + ((JavascriptExecutor) driver).executeScript("performance.clearResourceTimings();"); + click( + By.xpath( + destinationRow + "//button[@ng-click='deleteCopyField(field, name, field.name)']")); + + waitUntil( + "deleting a copy rule should retain the source's other destinations", + () -> copyFieldDestinations().equals(List.of(COPY_DEST_ONE))); + assertBrowserRequested(copyFieldPath + "/" + COPY_DEST_TWO); + assertNoSevereConsoleErrors(); + } finally { + List destinations = copyFieldDestinations(); + if (!destinations.isEmpty()) { + new SchemaRequest.DeleteCopyField(COPY_SOURCE, destinations) + .process(cluster.getSolrClient(), COLLECTION); + } + } + } + + private void assertBrowserRequested(String path) throws Exception { + waitUntil( + "the browser should request " + path, + () -> + ((List) + ((JavascriptExecutor) driver) + .executeScript( + "return performance.getEntriesByType('resource')" + + ".map(entry => new URL(entry.name).pathname);")) + .contains(path)); + } + + @Test + public void testCopyFieldRequiresSource() throws Exception { + openPage(COLLECTION + "/schema", By.id("schema")); + openAddCopyFieldDialog(); + waitFor(By.id("add_dest")).sendKeys(COPY_DEST_TWO); + click(By.xpath("//button[@ng-click='addCopyField()']")); + + waitForTextContains(By.cssSelector("div[ng-repeat='error in addCopyFieldErrors']"), "source"); + assertNoSevereConsoleErrors(); + } + + @Test + public void testCopyFieldRequiresDestination() throws Exception { + openPage(COLLECTION + "/schema", By.id("schema")); + openAddCopyFieldDialog(); + waitFor(By.id("add_source")).sendKeys(COPY_SOURCE); + click(By.xpath("//button[@ng-click='addCopyField()']")); + + waitForTextContains( + By.cssSelector("div[ng-repeat='error in addCopyFieldErrors']"), "destination"); + assertNoSevereConsoleErrors(); + } + + private void openAddCopyFieldDialog() throws InterruptedException { + click(By.id("addCopyField")); + WebElement source = waitFor(By.id("add_source")); + waitUntil( + "the copy-field dialog should focus the source input", + () -> source.equals(driver.switchTo().activeElement())); + } + + @SuppressWarnings("unchecked") + private List copyFieldDestinations() { + try { + NamedList response = + adminApi("/" + COLLECTION + "/schema/copyfields", params("source.fl", COPY_SOURCE)); + List> rules = (List>) response.get("copyFields"); + return rules.stream().map(rule -> (String) rule.get("dest")).sorted().toList(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + @SuppressWarnings("unchecked") private boolean fieldExists(String fieldName) { try { diff --git a/solr/webapp/web/js/angular/controllers/schema.js b/solr/webapp/web/js/angular/controllers/schema.js index 0e1741bab2be..ab07e0a53448 100644 --- a/solr/webapp/web/js/angular/controllers/schema.js +++ b/solr/webapp/web/js/angular/controllers/schema.js @@ -286,14 +286,13 @@ solrAdminApp.controller('SchemaController', } $scope.addCopyField = function() { delete $scope.addCopyFieldErrors; + if (!$scope.copyField.source || !$scope.copyField.dest) { + $scope.addCopyFieldErrors = ["Both source and destination fields are required."]; + return; + } var indexType = $scope.isCloudEnabled ? "collections" : "cores"; - var schemaChange = [{ - operationType: "add-copy-field", - source: $scope.copyField.source, - destinations: [$scope.copyField.dest] - }]; - SchemaV2.bulkSchemaModification(indexType, $routeParams.core, {schemaChange: schemaChange}, - function(error, data, response) { + SchemaV2.appendCopyFields(indexType, $routeParams.core, $scope.copyField.source, + {destinations: [$scope.copyField.dest]}, function(error, data, response) { $timeout(function() { if (error || (data && data.error)) { if (response && (response.status === 401 || response.status === 403)) { @@ -345,12 +344,7 @@ solrAdminApp.controller('SchemaController', } $scope.deleteCopyField = function(field, source, dest) { var indexType = $scope.isCloudEnabled ? "collections" : "cores"; - var schemaChange = [{ - operationType: "delete-copy-field", - source: source, - destinations: [dest] - }]; - SchemaV2.bulkSchemaModification(indexType, $routeParams.core, {schemaChange: schemaChange}, + SchemaV2.deleteCopyFieldsByDestination(indexType, $routeParams.core, source, dest, function(error, data, response) { $timeout(function() { if (error || (data && data.error)) { From 7cb9963387f4e929a656450ce602cfd62acd16ad Mon Sep 17 00:00:00 2001 From: Eric Pugh Date: Sun, 22 Nov 2026 09:01:50 -0500 Subject: [PATCH 7/8] SOLR-18479: Support individual copy-field destination limits --- .../SOLR-18479-v2-copyfield-api.yml | 3 +- .../client/api/endpoint/UpdateSchemaApi.java | 8 +- .../api/model/CopyFieldDestination.java | 27 ++ .../solr/handler/admin/api/UpdateSchema.java | 70 +++-- .../handler/admin/api/V2CopyFieldApiTest.java | 249 ++++++++++++++---- .../api/V2UpdateSchemaErrorCaseTests.java | 14 +- .../indexing-guide/pages/schema-api.adoc | 23 +- .../solr/webapp/AdminUiSchemaScreenTest.java | 12 +- .../web/js/angular/controllers/schema.js | 6 +- solr/webapp/web/partials/schema.html | 7 +- 10 files changed, 316 insertions(+), 103 deletions(-) create mode 100644 solr/api/src/java/org/apache/solr/client/api/model/CopyFieldDestination.java diff --git a/changelog/unreleased/SOLR-18479-v2-copyfield-api.yml b/changelog/unreleased/SOLR-18479-v2-copyfield-api.yml index 30cfc02de6dd..b182cdd8c8ab 100644 --- a/changelog/unreleased/SOLR-18479-v2-copyfield-api.yml +++ b/changelog/unreleased/SOLR-18479-v2-copyfield-api.yml @@ -3,7 +3,8 @@ title: > `/api/collections//schema/copyfields/`. Previously copy-fields were the one schema resource reachable only through the bulk endpoint. Rules are addressed by their source field: `GET` lists that source's rules, `PUT` sets its - complete `destinations` list, `POST` appends destinations without disturbing existing rules, + complete list of destination objects, each with its own optional `maxChars`, + `POST` appends destinations without disturbing existing rules, and `DELETE` removes them -- either all of them, or the ones named in a trailing comma-separated path segment. The Admin UI uses these endpoints to add and delete copy-field rules. diff --git a/solr/api/src/java/org/apache/solr/client/api/endpoint/UpdateSchemaApi.java b/solr/api/src/java/org/apache/solr/client/api/endpoint/UpdateSchemaApi.java index 6abb947cbbec..039612eb3ca4 100644 --- a/solr/api/src/java/org/apache/solr/client/api/endpoint/UpdateSchemaApi.java +++ b/solr/api/src/java/org/apache/solr/client/api/endpoint/UpdateSchemaApi.java @@ -29,7 +29,7 @@ import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import java.util.List; -import org.apache.solr.client.api.model.AddCopyFieldOperation; +import org.apache.solr.client.api.model.CopyFieldDestination; import org.apache.solr.client.api.model.SchemaChange; import org.apache.solr.client.api.model.SolrJerseyResponse; import org.apache.solr.client.api.model.UpsertDynamicFieldOperation; @@ -121,12 +121,12 @@ SolrJerseyResponse deleteFieldType(@PathParam("fieldTypeName") String fieldTypeN @StoreApiParameters @Operation( summary = - "Set the copy-field rules for the specified source field. The given destinations " + "Set the copy-field rules for the specified source field, with a character limit per destination. The given destinations " + "replace any rules that source already has.", tags = {"schema"}) SolrJerseyResponse upsertCopyFields( @PathParam("sourceField") String sourceField, - @RequestBody(required = true) AddCopyFieldOperation requestBody) + @RequestBody(required = true) List requestBody) throws Exception; @POST @@ -139,7 +139,7 @@ SolrJerseyResponse upsertCopyFields( tags = {"schema"}) SolrJerseyResponse appendCopyFields( @PathParam("sourceField") String sourceField, - @RequestBody(required = true) AddCopyFieldOperation requestBody) + @RequestBody(required = true) List requestBody) throws Exception; @DELETE diff --git a/solr/api/src/java/org/apache/solr/client/api/model/CopyFieldDestination.java b/solr/api/src/java/org/apache/solr/client/api/model/CopyFieldDestination.java new file mode 100644 index 000000000000..5e25d268a2f2 --- /dev/null +++ b/solr/api/src/java/org/apache/solr/client/api/model/CopyFieldDestination.java @@ -0,0 +1,27 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.solr.client.api.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** A destination and its optional character limit for a v2 copy-field rule. */ +public class CopyFieldDestination { + @JsonProperty(required = true) + public String dest; + + @JsonProperty public Integer maxChars; +} diff --git a/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java b/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java index 5ac20e491340..aa6747d5433c 100644 --- a/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java +++ b/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java @@ -20,7 +20,9 @@ import static org.apache.solr.common.util.CommandOperation.ERR_MSGS; import jakarta.inject.Inject; +import java.util.ArrayList; import java.util.Arrays; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -29,6 +31,7 @@ import org.apache.solr.api.JerseyResource; import org.apache.solr.client.api.endpoint.UpdateSchemaApi; import org.apache.solr.client.api.model.AddCopyFieldOperation; +import org.apache.solr.client.api.model.CopyFieldDestination; import org.apache.solr.client.api.model.DeleteCopyFieldOperation; import org.apache.solr.client.api.model.DeleteDynamicFieldOperation; import org.apache.solr.client.api.model.DeleteFieldOperation; @@ -159,15 +162,15 @@ public SolrJerseyResponse deleteFieldType(String fieldTypeName) throws Exception @Override @PermissionName(PermissionNameProvider.Name.SCHEMA_EDIT_PERM) - public SolrJerseyResponse upsertCopyFields(String sourceField, AddCopyFieldOperation requestBody) - throws Exception { + public SolrJerseyResponse upsertCopyFields( + String sourceField, List requestBody) throws Exception { return runCopyFieldOperation(sourceField, requestBody, "upsert-copy-field"); } @Override @PermissionName(PermissionNameProvider.Name.SCHEMA_EDIT_PERM) - public SolrJerseyResponse appendCopyFields(String sourceField, AddCopyFieldOperation requestBody) - throws Exception { + public SolrJerseyResponse appendCopyFields( + String sourceField, List requestBody) throws Exception { return runCopyFieldOperation(sourceField, requestBody, "append-copy-field"); } @@ -178,19 +181,33 @@ public SolrJerseyResponse appendCopyFields(String sourceField, AddCopyFieldOpera * refreshed under the update lock; doing it here would go stale whenever SchemaManager retries. */ private SolrJerseyResponse runCopyFieldOperation( - String sourceField, AddCopyFieldOperation requestBody, String operationType) + String sourceField, List requestBody, String operationType) throws Exception { final var response = instantiateJerseyResponse(SolrJerseyResponse.class); ensureSchemaMutable(); ensureRequiredParameterProvided("sourceField", sourceField); ensureRequiredRequestBodyProvided(requestBody); - ensureRequiredParameterProvided("destinations", requestBody.destinations); - ensureBodySourceAgreesWithPath(sourceField, requestBody.source); - - requestBody.source = sourceField; - requestBody.operationType = operationType; - - runWithSchemaManager(List.of(requestBody)); + final List operations = new ArrayList<>(); + if (operationType.equals("upsert-copy-field")) { + final var clear = new AddCopyFieldOperation(); + clear.source = sourceField; + clear.destinations = List.of(); + clear.operationType = operationType; + operations.add(clear); + } + final var destinations = new HashSet(); + for (CopyFieldDestination rule : requestBody) { + ensureRequiredParameterProvided("dest", rule == null ? null : rule.dest); + if (!destinations.add(rule.dest)) { + throw new SolrException( + SolrException.ErrorCode.BAD_REQUEST, "Duplicate destination: " + rule.dest); + } + final var add = copyFieldOperation(sourceField, rule.dest, rule.maxChars); + add.operationType = + operationType.equals("upsert-copy-field") ? "add-copy-field" : operationType; + operations.add(add); + } + runWithSchemaManager(operations); return response; } @@ -210,9 +227,7 @@ public SolrJerseyResponse deleteCopyFields(String sourceField) throws Exception } // Replacing the source's rules with none removes all of them. - final var clearOp = new AddCopyFieldOperation(); - clearOp.destinations = List.of(); - return runCopyFieldOperation(sourceField, clearOp, "upsert-copy-field"); + return runCopyFieldOperation(sourceField, List.of(), "upsert-copy-field"); } @Override @@ -248,17 +263,22 @@ private SolrJerseyResponse removeCopyFields(String sourceField, List des return response; } - /** Rejects a request body whose 'source' contradicts the source named in the path. */ - private void ensureBodySourceAgreesWithPath(String sourceField, String bodySource) { - if (bodySource != null && !bodySource.equals(sourceField)) { - throw new SolrException( - SolrException.ErrorCode.BAD_REQUEST, - "Request body source '" - + bodySource - + "' does not match the source in the path, '" - + sourceField - + "'"); + private AddCopyFieldOperation copyFieldOperation( + String source, String destination, Integer maxChars) { + ensureRequiredParameterProvided("source", source); + ensureRequiredParameterProvided("dest", destination); + if (destination.isBlank()) { + throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "destination must not be blank"); + } + if (maxChars != null && maxChars < 0) { + throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "maxChars must not be negative"); } + final var operation = new AddCopyFieldOperation(); + operation.source = source; + operation.destinations = List.of(destination); + operation.maxChars = maxChars; + operation.operationType = "add-copy-field"; + return operation; } /** diff --git a/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java b/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java index 12fb68730488..0f40d15316c8 100644 --- a/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java +++ b/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java @@ -16,18 +16,23 @@ */ package org.apache.solr.handler.admin.api; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import org.apache.solr.client.api.model.CopyFieldDestination; import org.apache.solr.client.api.model.IndexType; import org.apache.solr.client.solrj.RemoteSolrException; +import org.apache.solr.client.solrj.SolrRequest; import org.apache.solr.client.solrj.request.CollectionAdminRequest; +import org.apache.solr.client.solrj.request.GenericSolrRequest; import org.apache.solr.client.solrj.request.SchemaApi; import org.apache.solr.client.solrj.request.V2Request; import org.apache.solr.client.solrj.request.schema.SchemaRequest; import org.apache.solr.cloud.SolrCloudTestCase; import org.apache.solr.common.params.MapSolrParams; -import org.apache.solr.common.util.NamedList; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -62,13 +67,24 @@ public static void setupCluster() throws Exception { public void clearCopyFields() throws Exception { // A replace with no destinations clears the source whether or not it currently has rules, // so unlike DELETE this needs no special case for the empty state. - putCopyFields(SOURCE, Map.of("destinations", List.of())); + putCopyFields(SOURCE, rules()); } private static String schemaPath(String suffix) { return "/collections/" + COLLECTION + "/schema" + suffix; } + private static List> rules(String... destinations) { + return Arrays.stream(destinations).map(destination -> Map.of("dest", destination)).toList(); + } + + private static CopyFieldDestination destination(String field, Integer maxChars) { + final var destination = new CopyFieldDestination(); + destination.dest = field; + destination.maxChars = maxChars; + return destination; + } + private static void putCopyFields(String source, Object payload) throws Exception { new V2Request.Builder(schemaPath("/copyfields/" + source)) .PUT() @@ -122,20 +138,164 @@ private static List destinationsOf(String source) throws Exception { .collect(Collectors.toList()); } + @Test + public void testPutUsesIndividualDestinationLimits() throws Exception { + putCopyFields( + SOURCE, + List.of( + Map.of("dest", DEST_ONE, "maxChars", 100), Map.of("dest", DEST_TWO, "maxChars", 20))); + + var response = + new V2Request.Builder(schemaPath("/copyfields/" + SOURCE)) + .GET() + .build() + .process(cluster.getSolrClient()); + assertEquals( + List.of( + Map.of("source", SOURCE, "dest", DEST_ONE, "maxChars", 100), + Map.of("source", SOURCE, "dest", DEST_TWO, "maxChars", 20)), + response.getResponse().get("copyFields")); + + var legacy = new SchemaRequest.CopyFields().process(cluster.getSolrClient(), COLLECTION); + assertEquals( + List.of( + Map.of("source", SOURCE, "dest", DEST_ONE, "maxChars", 100), + Map.of("source", SOURCE, "dest", DEST_TWO, "maxChars", 20)), + ((List) legacy.getResponse().get("copyFields")) + .stream().filter(rule -> SOURCE.equals(((Map) rule).get("source"))).toList()); + } + + @Test + public void testPostPreservesExistingLimitsAndAddsIndividualLimits() throws Exception { + putCopyFields(SOURCE, List.of(Map.of("dest", DEST_ONE, "maxChars", 100))); + postCopyFields( + SOURCE, + List.of(Map.of("dest", DEST_ONE, "maxChars", 1), Map.of("dest", DEST_TWO, "maxChars", 20))); + var response = + new SchemaApi.ListCopyFieldsBySource(IndexType.COLLECTION, COLLECTION, SOURCE) + .process(cluster.getSolrClient()); + assertEquals( + List.of( + Map.of("source", SOURCE, "dest", DEST_ONE, "maxChars", 100), + Map.of("source", SOURCE, "dest", DEST_TWO, "maxChars", 20)), + response.copyFields); + } + + @Test + public void testPutChangesLimitsAndSupportsUnlimitedDestination() throws Exception { + putCopyFields(SOURCE, List.of(Map.of("dest", DEST_ONE, "maxChars", 100))); + putCopyFields( + SOURCE, List.of(Map.of("dest", DEST_ONE, "maxChars", 20), Map.of("dest", DEST_TWO))); + var response = + new SchemaApi.ListCopyFieldsBySource(IndexType.COLLECTION, COLLECTION, SOURCE) + .process(cluster.getSolrClient()); + assertEquals( + List.of( + Map.of("source", SOURCE, "dest", DEST_ONE, "maxChars", 20), + Map.of("source", SOURCE, "dest", DEST_TWO)), + response.copyFields); + } + + @Test + public void testFailedMultiDestinationPutAndPostAreAtomic() throws Exception { + putCopyFields(SOURCE, List.of(Map.of("dest", DEST_ONE, "maxChars", 100))); + var invalidRules = + List.of( + Map.of("dest", DEST_TWO, "maxChars", 20), Map.of("dest", "no_such_destination_field")); + expectThrows(RemoteSolrException.class, () -> putCopyFields(SOURCE, invalidRules)); + expectThrows(RemoteSolrException.class, () -> postCopyFields(SOURCE, invalidRules)); + var response = + new SchemaApi.ListCopyFieldsBySource(IndexType.COLLECTION, COLLECTION, SOURCE) + .process(cluster.getSolrClient()); + assertEquals( + List.of(Map.of("source", SOURCE, "dest", DEST_ONE, "maxChars", 100)), response.copyFields); + } + + @Test + public void testInvalidDestinationListsLeaveRulesIntact() throws Exception { + putCopyFields(SOURCE, rules(DEST_ONE)); + var nullRule = new ArrayList(); + nullRule.add(null); + for (Object invalid : + List.of( + List.of(Map.of("dest", DEST_TWO, "maxChars", -1)), + List.of(Map.of("dest", "")), + List.of(Map.of("dest", " ")), + rules(DEST_TWO, DEST_TWO), + nullRule, + List.of(Map.of("maxChars", 10)), + List.of(Map.of("destinations", List.of(DEST_TWO))))) { + assertEquals( + 400, + expectThrows(RemoteSolrException.class, () -> putCopyFields(SOURCE, invalid)).code()); + assertEquals( + 400, + expectThrows(RemoteSolrException.class, () -> postCopyFields(SOURCE, invalid)).code()); + assertEquals(List.of(DEST_ONE), destinationsOf(SOURCE)); + } + } + + @Test + public void testV1StillAcceptsScalarDest() throws Exception { + var request = + new GenericSolrRequest(SolrRequest.METHOD.POST, "/schema") + .setRequiresCollection(true) + .withContent( + ("{\"add-copy-field\":{\"source\":\"" + + SOURCE + + "\",\"dest\":\"" + + DEST_ONE + + "\",\"maxChars\":20}}") + .getBytes(StandardCharsets.UTF_8), + "application/json"); + request.process(cluster.getSolrClient(), COLLECTION); + assertEquals( + List.of(Map.of("source", SOURCE, "dest", DEST_ONE, "maxChars", 20)), + new SchemaRequest.CopyFields(params("source.fl", SOURCE)) + .process(cluster.getSolrClient(), COLLECTION) + .getCopyFields()); + } + + @Test + public void testDynamicSourceSupportsIndividualLimits() throws Exception { + String source = "*_s"; + try { + putCopyFields( + source, + List.of( + Map.of("dest", DEST_ONE, "maxChars", 100), Map.of("dest", DEST_TWO, "maxChars", 20))); + var response = + new SchemaApi.ListCopyFieldsBySource(IndexType.COLLECTION, COLLECTION, source) + .process(cluster.getSolrClient()); + assertEquals( + List.of( + Map.of("source", source, "dest", DEST_ONE, "maxChars", 100), + Map.of("source", source, "dest", DEST_TWO, "maxChars", 20)), + response.copyFields); + putCopyFields(source, List.of(Map.of("dest", DEST_TWO, "maxChars", 0))); + postCopyFields(source, List.of()); + response = + new SchemaApi.ListCopyFieldsBySource(IndexType.COLLECTION, COLLECTION, source) + .process(cluster.getSolrClient()); + assertEquals(List.of(Map.of("source", source, "dest", DEST_TWO)), response.copyFields); + } finally { + putCopyFields(source, List.of()); + } + } + @Test public void testAddAndListCopyFieldsBySource() throws Exception { - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + putCopyFields(SOURCE, rules(DEST_ONE, DEST_TWO)); assertEquals(List.of(DEST_ONE, DEST_TWO), destinationsOf(SOURCE)); } @Test public void testGeneratedPutReplacesCopyFields() throws Exception { - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + putCopyFields(SOURCE, rules(DEST_ONE, DEST_TWO)); var request = new SchemaApi.UpsertCopyFields(IndexType.COLLECTION, COLLECTION, SOURCE); - request.setDestinations(List.of(DEST_TWO)); - request.setMaxChars(100); + request.addCopyFieldDestination(destination(DEST_TWO, 100)); assertEquals(0, request.process(cluster.getSolrClient()).responseHeader.status); var response = @@ -147,11 +307,10 @@ public void testGeneratedPutReplacesCopyFields() throws Exception { @Test public void testGeneratedPostAppendsCopyFields() throws Exception { - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); + putCopyFields(SOURCE, rules(DEST_ONE)); var request = new SchemaApi.AppendCopyFields(IndexType.COLLECTION, COLLECTION, SOURCE); - request.setDestinations(List.of(DEST_TWO)); - request.setMaxChars(100); + request.addCopyFieldDestination(destination(DEST_TWO, 100)); assertEquals(0, request.process(cluster.getSolrClient()).responseHeader.status); var response = @@ -166,8 +325,8 @@ public void testGeneratedPostAppendsCopyFields() throws Exception { @Test public void testRepeatedPutIsIdempotent() throws Exception { - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + putCopyFields(SOURCE, rules(DEST_ONE, DEST_TWO)); + putCopyFields(SOURCE, rules(DEST_ONE, DEST_TWO)); // 'add-copy-field' on its own would append a second, duplicate rule for each destination, // making the source get copied twice over at index time. @@ -176,9 +335,9 @@ public void testRepeatedPutIsIdempotent() throws Exception { @Test public void testPutReplacesTheSourcesExistingRules() throws Exception { - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + putCopyFields(SOURCE, rules(DEST_ONE, DEST_TWO)); - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_TWO))); + putCopyFields(SOURCE, rules(DEST_TWO)); assertEquals( "destinations left out of the request should be gone", @@ -188,20 +347,19 @@ public void testPutReplacesTheSourcesExistingRules() throws Exception { @Test public void testPutCanExtendTheSourcesExistingRules() throws Exception { - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); + putCopyFields(SOURCE, rules(DEST_ONE)); - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + putCopyFields(SOURCE, rules(DEST_ONE, DEST_TWO)); assertEquals(List.of(DEST_ONE, DEST_TWO), destinationsOf(SOURCE)); } @Test public void testFailedPutLeavesExistingRulesIntact() throws Exception { - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); + putCopyFields(SOURCE, rules(DEST_ONE)); expectThrows( - RemoteSolrException.class, - () -> putCopyFields(SOURCE, Map.of("destinations", List.of("no_such_destination_field")))); + RemoteSolrException.class, () -> putCopyFields(SOURCE, rules("no_such_destination_field"))); assertEquals( "a rejected replacement must not drop the rules it would have replaced", @@ -211,14 +369,14 @@ public void testFailedPutLeavesExistingRulesIntact() throws Exception { @Test public void testAddAcceptsSingleDestinationAndMaxChars() throws Exception { - putCopyFields(SOURCE, Map.of("destinations", DEST_ONE, "maxChars", 100)); + putCopyFields(SOURCE, List.of(Map.of("dest", DEST_ONE, "maxChars", 100))); assertEquals(List.of(DEST_ONE), destinationsOf(SOURCE)); } @Test public void testDeleteNarrowedByDestinationParam() throws Exception { - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + putCopyFields(SOURCE, rules(DEST_ONE, DEST_TWO)); deleteCopyFields(SOURCE, DEST_ONE); @@ -230,7 +388,7 @@ public void testDeleteNarrowedByDestinationParam() throws Exception { @Test public void testUnqualifiedDeleteRemovesEveryRuleForTheSource() throws Exception { - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + putCopyFields(SOURCE, rules(DEST_ONE, DEST_TWO)); deleteCopyFields(SOURCE); @@ -239,7 +397,7 @@ public void testUnqualifiedDeleteRemovesEveryRuleForTheSource() throws Exception @Test public void testDeleteLeavesRulesWithOtherSourcesAlone() throws Exception { - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); + putCopyFields(SOURCE, rules(DEST_ONE)); deleteCopyFields(SOURCE); @@ -260,7 +418,7 @@ public void testDeleteOfUnknownSourceIsNotFound() throws Exception { @Test public void testGetBySourceReturnsOnlyThatSourcesDestinations() throws Exception { - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + putCopyFields(SOURCE, rules(DEST_ONE, DEST_TWO)); assertEquals(List.of(DEST_ONE, DEST_TWO), destinationsViaSourceEndpoint(SOURCE)); assertEquals(List.of("id_prefix"), destinationsViaSourceEndpoint("id")); @@ -273,19 +431,19 @@ public void testGetBySourceIsEmptyForASourceWithNoRules() throws Exception { @Test public void testPostAppendsWithoutDisturbingExistingRules() throws Exception { - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); + putCopyFields(SOURCE, rules(DEST_ONE)); - postCopyFields(SOURCE, Map.of("destinations", List.of(DEST_TWO))); + postCopyFields(SOURCE, rules(DEST_TWO)); assertEquals(List.of(DEST_ONE, DEST_TWO), destinationsOf(SOURCE)); } @Test public void testPostSkipsDestinationsAlreadyPresent() throws Exception { - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); + putCopyFields(SOURCE, rules(DEST_ONE)); - postCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); - postCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + postCopyFields(SOURCE, rules(DEST_ONE, DEST_TWO)); + postCopyFields(SOURCE, rules(DEST_ONE, DEST_TWO)); // A repeated append must not leave the source copied twice over. assertEquals(List.of(DEST_ONE, DEST_TWO), destinationsOf(SOURCE)); @@ -293,7 +451,7 @@ public void testPostSkipsDestinationsAlreadyPresent() throws Exception { @Test public void testDeleteOfSeveralDestinationsInOnePathSegment() throws Exception { - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + putCopyFields(SOURCE, rules(DEST_ONE, DEST_TWO)); deleteCopyFields(SOURCE, DEST_ONE, DEST_TWO); @@ -302,7 +460,7 @@ public void testDeleteOfSeveralDestinationsInOnePathSegment() throws Exception { @Test public void testDeleteOfMissingNamedRuleIsNotFound() throws Exception { - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); + putCopyFields(SOURCE, rules(DEST_ONE)); var thrown = expectThrows(RemoteSolrException.class, () -> deleteCopyFields(SOURCE, DEST_TWO)); @@ -322,7 +480,7 @@ public void testDeleteOfNamedRuleWithUnknownSourceIsNotFound() throws Exception @Test public void testDeleteOfMissingNamedRuleLeavesOtherRulesIntact() throws Exception { - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); + putCopyFields(SOURCE, rules(DEST_ONE)); var thrown = expectThrows(RemoteSolrException.class, () -> deleteCopyFields(SOURCE, DEST_ONE, DEST_TWO)); @@ -333,7 +491,7 @@ public void testDeleteOfMissingNamedRuleLeavesOtherRulesIntact() throws Exceptio @Test public void testDeleteOfInvalidDestinationGlobIsBadRequest() throws Exception { - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); + putCopyFields(SOURCE, rules(DEST_ONE)); var thrown = expectThrows(RemoteSolrException.class, () -> deleteCopyFields(SOURCE, "invalid**glob")); @@ -379,16 +537,16 @@ public void testV1DeleteOfMissingRuleIsBadRequest() { @Test public void testPutWithNoDestinationsClearsTheSource() throws Exception { - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE, DEST_TWO))); + putCopyFields(SOURCE, rules(DEST_ONE, DEST_TWO)); - putCopyFields(SOURCE, Map.of("destinations", List.of())); + putCopyFields(SOURCE, rules()); assertEquals(List.of(), destinationsOf(SOURCE)); } @Test public void testDeleteRejectsAPathSegmentNamingNoDestinations() throws Exception { - putCopyFields(SOURCE, Map.of("destinations", List.of(DEST_ONE))); + putCopyFields(SOURCE, rules(DEST_ONE)); final var thrown = expectThrows( @@ -405,28 +563,13 @@ public void testDeleteRejectsAPathSegmentNamingNoDestinations() throws Exception } @Test - public void testBodySourceContradictingThePathIsRejected() { + public void testAddRequiresDestinations() throws Exception { final var thrown = expectThrows( RemoteSolrException.class, - () -> - putCopyFields( - SOURCE, - Map.of("source", "some_other_source", "destinations", List.of(DEST_ONE)))); + () -> putCopyFields(SOURCE, List.of(Map.of("maxChars", 100)))); assertEquals(400, thrown.code()); - assertTrue( - "unexpected message: " + thrown.getMessage(), - thrown.getMessage().contains("does not match the source in the path")); - } - - @Test - public void testAddRequiresDestinations() throws Exception { - final var thrown = - expectThrows(RemoteSolrException.class, () -> putCopyFields(SOURCE, new NamedList<>())); - - assertEquals(400, thrown.code()); - assertTrue( - "unexpected message: " + thrown.getMessage(), thrown.getMessage().contains("destinations")); + assertTrue("unexpected message: " + thrown.getMessage(), thrown.getMessage().contains("dest")); } } diff --git a/solr/core/src/test/org/apache/solr/handler/admin/api/V2UpdateSchemaErrorCaseTests.java b/solr/core/src/test/org/apache/solr/handler/admin/api/V2UpdateSchemaErrorCaseTests.java index 4b5521deee20..391e5126e767 100644 --- a/solr/core/src/test/org/apache/solr/handler/admin/api/V2UpdateSchemaErrorCaseTests.java +++ b/solr/core/src/test/org/apache/solr/handler/admin/api/V2UpdateSchemaErrorCaseTests.java @@ -23,7 +23,7 @@ import java.util.List; import org.apache.solr.SolrTestCase; -import org.apache.solr.client.api.model.AddCopyFieldOperation; +import org.apache.solr.client.api.model.CopyFieldDestination; import org.apache.solr.client.api.model.UpsertDynamicFieldOperation; import org.apache.solr.client.api.model.UpsertFieldOperation; import org.apache.solr.client.api.model.UpsertFieldTypeOperation; @@ -160,26 +160,26 @@ public void testDeleteFieldTypeOperationRequiresTypeName() { @Test public void testUpsertCopyFieldsOperationRequiresSourceAndDestinations() { - final var noSourceOp = new AddCopyFieldOperation(); - noSourceOp.destinations = List.of("someDestination"); + final var noSourceOp = new CopyFieldDestination(); + noSourceOp.dest = "someDestination"; var thrown = expectThrows( SolrException.class, () -> { - schemaApi.upsertCopyFields(null, noSourceOp); + schemaApi.upsertCopyFields(null, List.of(noSourceOp)); }); assertEquals(BAD_REQUEST.code, thrown.code()); assertThat(thrown.getMessage(), containsString("Missing required parameter: sourceField")); - final var noDestinationsOp = new AddCopyFieldOperation(); + final var noDestinationsOp = new CopyFieldDestination(); thrown = expectThrows( SolrException.class, () -> { - schemaApi.upsertCopyFields("someSourceField", noDestinationsOp); + schemaApi.upsertCopyFields("someSourceField", List.of(noDestinationsOp)); }); assertEquals(BAD_REQUEST.code, thrown.code()); - assertThat(thrown.getMessage(), containsString("Missing required parameter: destinations")); + assertThat(thrown.getMessage(), containsString("Missing required parameter: dest")); } @Test diff --git a/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc b/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc index f04c83843300..4233772a2ec2 100644 --- a/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc +++ b/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc @@ -495,7 +495,7 @@ s|Required |Default: none |=== + A field or an array of fields to which the source field will be copied. -In the v2 API this attribute is named `destinations`; `dest` is still accepted as an alias. +V2 per-source writes use one `dest` per rule, as shown below. `maxChars`:: + @@ -530,23 +530,26 @@ V2 API:: [source,bash] ---- curl -X PUT -H 'Content-type:application/json' --data-binary ' -{ - "destinations":[ "location", "catchall" ] -}' http://localhost:8983/api/collections/techproducts/schema/copyfields/shelf +[ + { "dest": "location", "maxChars": 100 }, + { "dest": "catchall", "maxChars": 20 } +]' http://localhost:8983/api/collections/techproducts/schema/copyfields/shelf ---- ==== ====== + Copy-field rules have no name of their own, so v2 addresses them by their source field: the source is the final path segment, and the body carries the destinations. -The v2 request attribute is `destinations`, though `dest` is accepted as an alias. +The body is an array of objects, each with a required `dest` and an optional `maxChars`. +Each destination can have a different limit; omitting `maxChars` or setting it to `0` copies all characters. +Each destination must appear only once in the array. + [IMPORTANT] ==== `PUT` is a replace, not an append: the destinations you send become the complete set of copy-field rules for that source, and any rule left out is removed. Sending the same request twice is therefore safe. -Sending an empty `destinations` list removes every rule with that source. +Sending an empty array (`[]`) removes every rule with that source. ==== + To add destinations while leaving the source's existing rules alone, `POST` to the same path: @@ -554,13 +557,15 @@ To add destinations while leaving the source's existing rules alone, `POST` to t [source,bash] ---- curl -X POST -H 'Content-type:application/json' --data-binary ' -{ - "destinations":[ "catchall" ] -}' http://localhost:8983/api/collections/techproducts/schema/copyfields/shelf +[ + { "dest": "catchall", "maxChars": 20 } +]' http://localhost:8983/api/collections/techproducts/schema/copyfields/shelf ---- + Destinations that the source already copies to are ignored, so a repeated `POST` will not leave the source copied twice over. +An existing destination keeps its current `maxChars`; use `PUT` to change limits. +A failed `PUT` or `POST` leaves all existing rules intact. The `add-copy-field` command available through the bulk endpoint performs no such check. === Delete a Copy Field Rule diff --git a/solr/webapp/src/test/org/apache/solr/webapp/AdminUiSchemaScreenTest.java b/solr/webapp/src/test/org/apache/solr/webapp/AdminUiSchemaScreenTest.java index 800d16d3b9c0..40347d15b608 100644 --- a/solr/webapp/src/test/org/apache/solr/webapp/AdminUiSchemaScreenTest.java +++ b/solr/webapp/src/test/org/apache/solr/webapp/AdminUiSchemaScreenTest.java @@ -112,13 +112,14 @@ public void testAddAndDeleteFieldViaUi() throws Exception { @Test public void testCopyFieldsUseDedicatedEndpoints() throws Exception { - new SchemaRequest.AddCopyField(COPY_SOURCE, List.of(COPY_DEST_ONE)) + new SchemaRequest.AddCopyField(COPY_SOURCE, List.of(COPY_DEST_ONE), 100) .process(cluster.getSolrClient(), COLLECTION); try { openPage(COLLECTION + "/schema", By.id("schema")); openAddCopyFieldDialog(); waitFor(By.id("add_source")).sendKeys(COPY_SOURCE); waitFor(By.id("add_dest")).sendKeys(COPY_DEST_TWO); + waitFor(By.id("add_max_chars")).sendKeys("20"); ((JavascriptExecutor) driver).executeScript("performance.clearResourceTimings();"); click(By.xpath("//button[@ng-click='addCopyField()']")); @@ -127,6 +128,15 @@ public void testCopyFieldsUseDedicatedEndpoints() throws Exception { () -> copyFieldDestinations().equals(List.of(COPY_DEST_ONE, COPY_DEST_TWO))); String copyFieldPath = "/api/collections/" + COLLECTION + "/schema/copyfields/" + COPY_SOURCE; assertBrowserRequested(copyFieldPath); + var copyFields = + new SchemaRequest.CopyFields(params("source.fl", COPY_SOURCE)) + .process(cluster.getSolrClient(), COLLECTION) + .getCopyFields(); + assertEquals( + List.of( + Map.of("source", COPY_SOURCE, "dest", COPY_DEST_ONE, "maxChars", 100), + Map.of("source", COPY_SOURCE, "dest", COPY_DEST_TWO, "maxChars", 20)), + copyFields); openPage(COLLECTION + "/schema?field=" + COPY_SOURCE, By.id("schema")); waitForTextContains(By.cssSelector("#schema span.name"), COPY_SOURCE); diff --git a/solr/webapp/web/js/angular/controllers/schema.js b/solr/webapp/web/js/angular/controllers/schema.js index ab07e0a53448..6480d62e11b7 100644 --- a/solr/webapp/web/js/angular/controllers/schema.js +++ b/solr/webapp/web/js/angular/controllers/schema.js @@ -291,8 +291,12 @@ solrAdminApp.controller('SchemaController', return; } var indexType = $scope.isCloudEnabled ? "collections" : "cores"; + var rule = {dest: $scope.copyField.dest}; + if ($scope.copyField.maxChars != null) { + rule.maxChars = $scope.copyField.maxChars; + } SchemaV2.appendCopyFields(indexType, $routeParams.core, $scope.copyField.source, - {destinations: [$scope.copyField.dest]}, function(error, data, response) { + [rule], function(error, data, response) { $timeout(function() { if (error || (data && data.error)) { if (response && (response.status === 401 || response.status === 403)) { diff --git a/solr/webapp/web/partials/schema.html b/solr/webapp/web/partials/schema.html index e36c5fdf79b7..4c2d24066f25 100644 --- a/solr/webapp/web/partials/schema.html +++ b/solr/webapp/web/partials/schema.html @@ -186,7 +186,7 @@
    -
    +

    @@ -194,11 +194,14 @@

    +

    +

    +
    {{error}}

    - +

    From 34323664bd765ebe45105bcbccdeeeaca52099d8 Mon Sep 17 00:00:00 2001 From: Eric Pugh Date: Sun, 22 Nov 2026 09:06:00 -0500 Subject: [PATCH 8/8] SOLR-18479: Use destination consistently in v2 schema APIs --- .../unreleased/SOLR-18479-v2-destination.yml | 10 + .../api/model/AddCopyFieldOperation.java | 2 + .../client/api/model/AddCopyFieldRequest.java | 30 +++ .../api/model/CopyFieldDestination.java | 2 +- .../api/model/DeleteCopyFieldOperation.java | 2 + .../api/model/DeleteCopyFieldRequest.java | 28 +++ .../solr/client/api/model/SchemaChange.java | 4 +- ...chemaChangeOperationSerializationTest.java | 32 ++-- .../apache/solr/handler/SchemaHandler.java | 5 +- .../solr/handler/admin/api/GetSchema.java | 12 ++ .../handler/admin/api/GetSchemaField.java | 39 +++- .../solr/handler/admin/api/UpdateSchema.java | 30 ++- .../solr/schema/SchemaManagerUtils.java | 10 +- .../handler/admin/api/V2CopyFieldApiTest.java | 180 ++++++++++++++---- .../api/V2UpdateSchemaErrorCaseTests.java | 4 +- .../indexing-guide/pages/schema-api.adoc | 33 ++-- .../pages/major-changes-in-solr-11.adoc | 8 + .../web/js/angular/controllers/schema.js | 2 +- 18 files changed, 353 insertions(+), 80 deletions(-) create mode 100644 changelog/unreleased/SOLR-18479-v2-destination.yml create mode 100644 solr/api/src/java/org/apache/solr/client/api/model/AddCopyFieldRequest.java create mode 100644 solr/api/src/java/org/apache/solr/client/api/model/DeleteCopyFieldRequest.java diff --git a/changelog/unreleased/SOLR-18479-v2-destination.yml b/changelog/unreleased/SOLR-18479-v2-destination.yml new file mode 100644 index 000000000000..1b8391f1d930 --- /dev/null +++ b/changelog/unreleased/SOLR-18479-v2-destination.yml @@ -0,0 +1,10 @@ +title: > + The v2 Schema API uses `destination` for copy-field request and response properties, + and `destination.fl` for destination filtering. Each bulk copy-field operation addresses + one destination. The v1 Schema API retains its existing `dest` names and behavior. +type: changed +authors: + - name: Eric Pugh +links: + - name: SOLR-18479 + url: https://issues.apache.org/jira/browse/SOLR-18479 diff --git a/solr/api/src/java/org/apache/solr/client/api/model/AddCopyFieldOperation.java b/solr/api/src/java/org/apache/solr/client/api/model/AddCopyFieldOperation.java index 2efad0ea3aae..b81da8fa9e59 100644 --- a/solr/api/src/java/org/apache/solr/client/api/model/AddCopyFieldOperation.java +++ b/solr/api/src/java/org/apache/solr/client/api/model/AddCopyFieldOperation.java @@ -19,8 +19,10 @@ import com.fasterxml.jackson.annotation.JsonAlias; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; import java.util.List; +@JsonTypeInfo(use = JsonTypeInfo.Id.NONE) public class AddCopyFieldOperation extends SchemaChange { @JsonProperty public String source; diff --git a/solr/api/src/java/org/apache/solr/client/api/model/AddCopyFieldRequest.java b/solr/api/src/java/org/apache/solr/client/api/model/AddCopyFieldRequest.java new file mode 100644 index 000000000000..18a713d89efe --- /dev/null +++ b/solr/api/src/java/org/apache/solr/client/api/model/AddCopyFieldRequest.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.solr.client.api.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** A v2 bulk operation adding one copy-field destination. */ +public class AddCopyFieldRequest extends SchemaChange { + @JsonProperty(required = true) + public String source; + + @JsonProperty(required = true) + public String destination; + + @JsonProperty public Integer maxChars; +} diff --git a/solr/api/src/java/org/apache/solr/client/api/model/CopyFieldDestination.java b/solr/api/src/java/org/apache/solr/client/api/model/CopyFieldDestination.java index 5e25d268a2f2..5560b5faa703 100644 --- a/solr/api/src/java/org/apache/solr/client/api/model/CopyFieldDestination.java +++ b/solr/api/src/java/org/apache/solr/client/api/model/CopyFieldDestination.java @@ -21,7 +21,7 @@ /** A destination and its optional character limit for a v2 copy-field rule. */ public class CopyFieldDestination { @JsonProperty(required = true) - public String dest; + public String destination; @JsonProperty public Integer maxChars; } diff --git a/solr/api/src/java/org/apache/solr/client/api/model/DeleteCopyFieldOperation.java b/solr/api/src/java/org/apache/solr/client/api/model/DeleteCopyFieldOperation.java index 1d1ed970b465..98fc88a5d618 100644 --- a/solr/api/src/java/org/apache/solr/client/api/model/DeleteCopyFieldOperation.java +++ b/solr/api/src/java/org/apache/solr/client/api/model/DeleteCopyFieldOperation.java @@ -19,8 +19,10 @@ import com.fasterxml.jackson.annotation.JsonAlias; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; import java.util.List; +@JsonTypeInfo(use = JsonTypeInfo.Id.NONE) public class DeleteCopyFieldOperation extends SchemaChange { @JsonProperty public String source; diff --git a/solr/api/src/java/org/apache/solr/client/api/model/DeleteCopyFieldRequest.java b/solr/api/src/java/org/apache/solr/client/api/model/DeleteCopyFieldRequest.java new file mode 100644 index 000000000000..5adf359be16b --- /dev/null +++ b/solr/api/src/java/org/apache/solr/client/api/model/DeleteCopyFieldRequest.java @@ -0,0 +1,28 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.solr.client.api.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** A v2 bulk operation deleting one copy-field destination. */ +public class DeleteCopyFieldRequest extends SchemaChange { + @JsonProperty(required = true) + public String source; + + @JsonProperty(required = true) + public String destination; +} diff --git a/solr/api/src/java/org/apache/solr/client/api/model/SchemaChange.java b/solr/api/src/java/org/apache/solr/client/api/model/SchemaChange.java index 7a9265bd1193..e46fc60f57ce 100644 --- a/solr/api/src/java/org/apache/solr/client/api/model/SchemaChange.java +++ b/solr/api/src/java/org/apache/solr/client/api/model/SchemaChange.java @@ -40,8 +40,8 @@ @JsonSubTypes.Type(value = DeleteFieldTypeOperation.class, name = "delete-field-type"), @JsonSubTypes.Type(value = DeleteFieldOperation.class, name = "delete-field"), @JsonSubTypes.Type(value = DeleteDynamicFieldOperation.class, name = "delete-dynamic-field"), - @JsonSubTypes.Type(value = AddCopyFieldOperation.class, name = "add-copy-field"), - @JsonSubTypes.Type(value = DeleteCopyFieldOperation.class, name = "delete-copy-field"), + @JsonSubTypes.Type(value = AddCopyFieldRequest.class, name = "add-copy-field"), + @JsonSubTypes.Type(value = DeleteCopyFieldRequest.class, name = "delete-copy-field"), }) public class SchemaChange { diff --git a/solr/api/src/test/org/apache/solr/client/api/model/SchemaChangeOperationSerializationTest.java b/solr/api/src/test/org/apache/solr/client/api/model/SchemaChangeOperationSerializationTest.java index a0606bd6d3d7..4c90a8f95aef 100644 --- a/solr/api/src/test/org/apache/solr/client/api/model/SchemaChangeOperationSerializationTest.java +++ b/solr/api/src/test/org/apache/solr/client/api/model/SchemaChangeOperationSerializationTest.java @@ -77,23 +77,22 @@ public void testAddCopyField() throws Exception { { "operationType": "add-copy-field", "source": "source1", - "destinations": ["dest1", "dest2"], + "destination": "dest1", "maxChars": 123 } """; final var parsedGeneric = OBJECT_MAPPER.readValue(inputJson, SchemaChange.class); - assertThat(parsedGeneric, instanceOf(AddCopyFieldOperation.class)); - final var parsedSpecific = (AddCopyFieldOperation) parsedGeneric; + assertThat(parsedGeneric, instanceOf(AddCopyFieldRequest.class)); + final var parsedSpecific = (AddCopyFieldRequest) parsedGeneric; assertEquals("source1", parsedSpecific.source); - assertThat(parsedSpecific.destinations, contains("dest1", "dest2")); + assertEquals("dest1", parsedSpecific.destination); assertEquals(Integer.valueOf(123), parsedSpecific.maxChars); } - // "dest" is used instead of "destinations", to support v1 APIs @Test - public void testAddCopyFieldAltFieldName() throws Exception { + public void testV1AddCopyFieldDest() throws Exception { final var inputJson = """ { @@ -104,10 +103,7 @@ public void testAddCopyFieldAltFieldName() throws Exception { } """; - final var parsedGeneric = OBJECT_MAPPER.readValue(inputJson, SchemaChange.class); - - assertThat(parsedGeneric, instanceOf(AddCopyFieldOperation.class)); - final var parsedSpecific = (AddCopyFieldOperation) parsedGeneric; + final var parsedSpecific = OBJECT_MAPPER.readValue(inputJson, AddCopyFieldOperation.class); assertEquals("source1", parsedSpecific.source); assertThat(parsedSpecific.destinations, contains("dest1", "dest2")); assertEquals(Integer.valueOf(123), parsedSpecific.maxChars); @@ -183,21 +179,20 @@ public void testDeleteCopyField() throws Exception { { "operationType": "delete-copy-field", "source": "source1", - "destinations": ["dest1", "dest2"] + "destination": "dest1" } """; final var parsedGeneric = OBJECT_MAPPER.readValue(inputJson, SchemaChange.class); - assertThat(parsedGeneric, instanceOf(DeleteCopyFieldOperation.class)); - final var parsedSpecific = (DeleteCopyFieldOperation) parsedGeneric; + assertThat(parsedGeneric, instanceOf(DeleteCopyFieldRequest.class)); + final var parsedSpecific = (DeleteCopyFieldRequest) parsedGeneric; assertEquals("source1", parsedSpecific.source); - assertThat(parsedSpecific.destinations, contains("dest1", "dest2")); + assertEquals("dest1", parsedSpecific.destination); } - // "dest" is used instead of "destinations", to support v1 APIs @Test - public void testDeleteCopyFieldAltFieldName() throws Exception { + public void testV1DeleteCopyFieldDest() throws Exception { final var inputJson = """ { @@ -207,10 +202,7 @@ public void testDeleteCopyFieldAltFieldName() throws Exception { } """; - final var parsedGeneric = OBJECT_MAPPER.readValue(inputJson, SchemaChange.class); - - assertThat(parsedGeneric, instanceOf(DeleteCopyFieldOperation.class)); - final var parsedSpecific = (DeleteCopyFieldOperation) parsedGeneric; + final var parsedSpecific = OBJECT_MAPPER.readValue(inputJson, DeleteCopyFieldOperation.class); assertEquals("source1", parsedSpecific.source); assertThat(parsedSpecific.destinations, contains("dest1", "dest2")); } diff --git a/solr/core/src/java/org/apache/solr/handler/SchemaHandler.java b/solr/core/src/java/org/apache/solr/handler/SchemaHandler.java index 8bc108c59c6e..92855d5f240e 100644 --- a/solr/core/src/java/org/apache/solr/handler/SchemaHandler.java +++ b/solr/core/src/java/org/apache/solr/handler/SchemaHandler.java @@ -151,7 +151,7 @@ private void handleGET(SolrQueryRequest req, SolrQueryResponse rsp) { case "/schema": { V2ApiUtils.squashIntoSolrResponseWithoutHeader( - rsp, new GetSchema(req.getCore(), req.getSchema()).getSchemaInfo()); + rsp, new GetSchema(req.getCore(), req.getSchema()).getSchemaInfoForV1()); break; } case "/schema/version": @@ -216,7 +216,8 @@ private void handleGET(SolrQueryRequest req, SolrQueryResponse rsp) { case "copyfields": { V2ApiUtils.squashIntoSolrResponseWithoutHeader( - rsp, new GetSchemaField(req.getSchema(), req.getParams()).listCopyFields()); + rsp, + new GetSchemaField(req.getSchema(), req.getParams()).listCopyFieldsForV1()); return; } case "dynamicfields": diff --git a/solr/core/src/java/org/apache/solr/handler/admin/api/GetSchema.java b/solr/core/src/java/org/apache/solr/handler/admin/api/GetSchema.java index 7d914533b35a..f1e9565daedf 100644 --- a/solr/core/src/java/org/apache/solr/handler/admin/api/GetSchema.java +++ b/solr/core/src/java/org/apache/solr/handler/admin/api/GetSchema.java @@ -19,6 +19,8 @@ import jakarta.inject.Inject; import java.lang.invoke.MethodHandles; +import java.util.LinkedHashMap; +import java.util.List; import org.apache.solr.api.JerseyResource; import org.apache.solr.client.api.endpoint.GetSchemaApi; import org.apache.solr.client.api.model.SchemaInfoResponse; @@ -54,6 +56,16 @@ public GetSchema(SolrCore solrCore, IndexSchema indexSchema) { @Override @PermissionName(PermissionNameProvider.Name.SCHEMA_READ_PERM) public SchemaInfoResponse getSchemaInfo() { + final var response = getSchemaInfoForV1(); + response.schema = new LinkedHashMap<>(response.schema); + if (response.schema.get("copyFields") instanceof List rules) { + response.schema.put("copyFields", GetSchemaField.copyFieldsForV2(rules)); + } + return response; + } + + /** Returns the schema using the v1 copy-field names. */ + public SchemaInfoResponse getSchemaInfoForV1() { final var response = instantiateJerseyResponse(SchemaInfoResponse.class); response.schema = indexSchema.getNamedPropertyValues(); diff --git a/solr/core/src/java/org/apache/solr/handler/admin/api/GetSchemaField.java b/solr/core/src/java/org/apache/solr/handler/admin/api/GetSchemaField.java index b95fc3f6ab6f..d15c0e2cfff0 100644 --- a/solr/core/src/java/org/apache/solr/handler/admin/api/GetSchemaField.java +++ b/solr/core/src/java/org/apache/solr/handler/admin/api/GetSchemaField.java @@ -18,6 +18,7 @@ package org.apache.solr.handler.admin.api; import jakarta.inject.Inject; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; @@ -33,6 +34,7 @@ import org.apache.solr.common.MapWriter; import org.apache.solr.common.SolrException; import org.apache.solr.common.cloud.SolrClassLoader; +import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.params.SolrParams; import org.apache.solr.common.util.NamedList; import org.apache.solr.common.util.SimpleOrderedMap; @@ -101,6 +103,22 @@ public SchemaGetFieldInfoResponse getFieldInfo(String fieldName) { @Override @PermissionName(PermissionNameProvider.Name.SCHEMA_READ_PERM) public SchemaListCopyFieldsResponse listCopyFields() { + SolrParams copyFieldParams = params; + if (params.getParams("destination.fl") != null || params.getParams("dest.fl") != null) { + final var translated = new ModifiableSolrParams(params); + translated.remove("dest.fl"); + if (params.getParams("destination.fl") != null) { + translated.set("dest.fl", params.getParams("destination.fl")); + } + copyFieldParams = translated; + } + final var response = instantiateJerseyResponse(SchemaListCopyFieldsResponse.class); + response.copyFields = copyFieldsForV2(listAllFieldsOfType("copyfields", copyFieldParams)); + return response; + } + + /** Lists copy fields using the v1 response format. */ + public SchemaListCopyFieldsResponse listCopyFieldsForV1() { SchemaListCopyFieldsResponse response = instantiateJerseyResponse(SchemaListCopyFieldsResponse.class); final String realName = "copyfields"; @@ -117,7 +135,7 @@ public SchemaListCopyFieldsResponse listCopyFieldsBySource(String sourceField) { instantiateJerseyResponse(SchemaListCopyFieldsResponse.class); response.copyFields = - List.copyOf(indexSchema.getCopyFieldProperties(false, Set.of(sourceField), null)); + copyFieldsForV2(indexSchema.getCopyFieldProperties(false, Set.of(sourceField), null)); return response; } @@ -189,6 +207,25 @@ public SchemaGetFieldTypeInfoResponse getFieldTypeInfo(String fieldTypeName) { SolrException.ErrorCode.NOT_FOUND, "No such field type [" + fieldTypeName + "]"); } + static List copyFieldsForV2(List rules) { + final List result = new ArrayList<>(rules.size()); + for (Object rule : rules) { + final var renamed = new SimpleOrderedMap(); + ((Map) rule) + .forEach( + (key, value) -> + renamed.add( + switch (key.toString()) { + case "dest" -> "destination"; + case "destDynamicBase" -> "destinationDynamicBase"; + default -> key.toString(); + }, + value)); + result.add(renamed); + } + return result; + } + private List listAllFieldsOfType(String realName, SolrParams params) { String camelCaseRealName = IndexSchema.nameMapping.get(realName); Map propertyValues = indexSchema.getNamedPropertyValues(realName, params); diff --git a/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java b/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java index aa6747d5433c..db4f92ace9cc 100644 --- a/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java +++ b/solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java @@ -31,8 +31,10 @@ import org.apache.solr.api.JerseyResource; import org.apache.solr.client.api.endpoint.UpdateSchemaApi; import org.apache.solr.client.api.model.AddCopyFieldOperation; +import org.apache.solr.client.api.model.AddCopyFieldRequest; import org.apache.solr.client.api.model.CopyFieldDestination; import org.apache.solr.client.api.model.DeleteCopyFieldOperation; +import org.apache.solr.client.api.model.DeleteCopyFieldRequest; import org.apache.solr.client.api.model.DeleteDynamicFieldOperation; import org.apache.solr.client.api.model.DeleteFieldOperation; import org.apache.solr.client.api.model.DeleteFieldTypeOperation; @@ -197,12 +199,12 @@ private SolrJerseyResponse runCopyFieldOperation( } final var destinations = new HashSet(); for (CopyFieldDestination rule : requestBody) { - ensureRequiredParameterProvided("dest", rule == null ? null : rule.dest); - if (!destinations.add(rule.dest)) { + ensureRequiredParameterProvided("destination", rule == null ? null : rule.destination); + if (!destinations.add(rule.destination)) { throw new SolrException( - SolrException.ErrorCode.BAD_REQUEST, "Duplicate destination: " + rule.dest); + SolrException.ErrorCode.BAD_REQUEST, "Duplicate destination: " + rule.destination); } - final var add = copyFieldOperation(sourceField, rule.dest, rule.maxChars); + final var add = copyFieldOperation(sourceField, rule.destination, rule.maxChars); add.operationType = operationType.equals("upsert-copy-field") ? "add-copy-field" : operationType; operations.add(add); @@ -266,7 +268,7 @@ private SolrJerseyResponse removeCopyFields(String sourceField, List des private AddCopyFieldOperation copyFieldOperation( String source, String destination, Integer maxChars) { ensureRequiredParameterProvided("source", source); - ensureRequiredParameterProvided("dest", destination); + ensureRequiredParameterProvided("destination", destination); if (destination.isBlank()) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "destination must not be blank"); } @@ -304,7 +306,23 @@ public SolrJerseyResponse bulkSchemaModification(List requestBody) ensureSchemaMutable(); ensureRequiredRequestBodyProvided(requestBody); - runWithSchemaManager(requestBody); + final List operations = new ArrayList<>(); + for (SchemaChange change : requestBody) { + if (change instanceof AddCopyFieldRequest add) { + operations.add(copyFieldOperation(add.source, add.destination, add.maxChars)); + } else if (change instanceof DeleteCopyFieldRequest delete) { + ensureRequiredParameterProvided("source", delete.source); + ensureRequiredParameterProvided("destination", delete.destination); + final var operation = new DeleteCopyFieldOperation(); + operation.source = delete.source; + operation.destinations = List.of(delete.destination); + operation.operationType = "delete-copy-field"; + operations.add(operation); + } else { + operations.add(change); + } + } + runWithSchemaManager(operations); return response; } diff --git a/solr/core/src/java/org/apache/solr/schema/SchemaManagerUtils.java b/solr/core/src/java/org/apache/solr/schema/SchemaManagerUtils.java index 627b46caccec..462c506a8f92 100644 --- a/solr/core/src/java/org/apache/solr/schema/SchemaManagerUtils.java +++ b/solr/core/src/java/org/apache/solr/schema/SchemaManagerUtils.java @@ -20,6 +20,8 @@ import com.fasterxml.jackson.core.type.TypeReference; import java.util.Map; +import org.apache.solr.client.api.model.AddCopyFieldOperation; +import org.apache.solr.client.api.model.DeleteCopyFieldOperation; import org.apache.solr.client.api.model.SchemaChange; import org.apache.solr.common.SolrException; import org.apache.solr.common.util.CommandOperation; @@ -35,7 +37,13 @@ public static SchemaChange convertToSchemaChangeOperations(CommandOperation toCo final var operationData = toConvert.getDataMap(); operationData.put(OPERATION_TYPE_PROP, opName); - return SolrJacksonMapper.getObjectMapper().convertValue(operationData, SchemaChange.class); + Class operationClass = + switch (opName) { + case "add-copy-field" -> AddCopyFieldOperation.class; + case "delete-copy-field" -> DeleteCopyFieldOperation.class; + default -> SchemaChange.class; + }; + return SolrJacksonMapper.getObjectMapper().convertValue(operationData, operationClass); } // TODO This utility exists because ManagedIndexSchema currently consumes op data in "Map" form. diff --git a/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java b/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java index 0f40d15316c8..00da7098c665 100644 --- a/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java +++ b/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java @@ -22,7 +22,9 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import org.apache.solr.client.api.model.AddCopyFieldRequest; import org.apache.solr.client.api.model.CopyFieldDestination; +import org.apache.solr.client.api.model.DeleteCopyFieldRequest; import org.apache.solr.client.api.model.IndexType; import org.apache.solr.client.solrj.RemoteSolrException; import org.apache.solr.client.solrj.SolrRequest; @@ -75,12 +77,14 @@ private static String schemaPath(String suffix) { } private static List> rules(String... destinations) { - return Arrays.stream(destinations).map(destination -> Map.of("dest", destination)).toList(); + return Arrays.stream(destinations) + .map(destination -> Map.of("destination", destination)) + .toList(); } private static CopyFieldDestination destination(String field, Integer maxChars) { final var destination = new CopyFieldDestination(); - destination.dest = field; + destination.destination = field; destination.maxChars = maxChars; return destination; } @@ -118,7 +122,7 @@ private static List destinationsViaSourceEndpoint(String source) throws .build() .process(cluster.getSolrClient()); final var copyFields = (List>) response.getResponse().get("copyFields"); - return copyFields.stream().map(rule -> (String) rule.get("dest")).sorted().toList(); + return copyFields.stream().map(rule -> (String) rule.get("destination")).sorted().toList(); } /** Destinations of every copy-field rule currently declared with the given source. */ @@ -133,7 +137,7 @@ private static List destinationsOf(String source) throws Exception { final var copyFields = (List>) response.getResponse().get("copyFields"); return copyFields.stream() .filter(rule -> source.equals(rule.get("source"))) - .map(rule -> (String) rule.get("dest")) + .map(rule -> (String) rule.get("destination")) .sorted() .collect(Collectors.toList()); } @@ -143,7 +147,8 @@ public void testPutUsesIndividualDestinationLimits() throws Exception { putCopyFields( SOURCE, List.of( - Map.of("dest", DEST_ONE, "maxChars", 100), Map.of("dest", DEST_TWO, "maxChars", 20))); + Map.of("destination", DEST_ONE, "maxChars", 100), + Map.of("destination", DEST_TWO, "maxChars", 20))); var response = new V2Request.Builder(schemaPath("/copyfields/" + SOURCE)) @@ -152,8 +157,8 @@ public void testPutUsesIndividualDestinationLimits() throws Exception { .process(cluster.getSolrClient()); assertEquals( List.of( - Map.of("source", SOURCE, "dest", DEST_ONE, "maxChars", 100), - Map.of("source", SOURCE, "dest", DEST_TWO, "maxChars", 20)), + Map.of("source", SOURCE, "destination", DEST_ONE, "maxChars", 100), + Map.of("source", SOURCE, "destination", DEST_TWO, "maxChars", 20)), response.getResponse().get("copyFields")); var legacy = new SchemaRequest.CopyFields().process(cluster.getSolrClient(), COLLECTION); @@ -167,48 +172,53 @@ public void testPutUsesIndividualDestinationLimits() throws Exception { @Test public void testPostPreservesExistingLimitsAndAddsIndividualLimits() throws Exception { - putCopyFields(SOURCE, List.of(Map.of("dest", DEST_ONE, "maxChars", 100))); + putCopyFields(SOURCE, List.of(Map.of("destination", DEST_ONE, "maxChars", 100))); postCopyFields( SOURCE, - List.of(Map.of("dest", DEST_ONE, "maxChars", 1), Map.of("dest", DEST_TWO, "maxChars", 20))); + List.of( + Map.of("destination", DEST_ONE, "maxChars", 1), + Map.of("destination", DEST_TWO, "maxChars", 20))); var response = new SchemaApi.ListCopyFieldsBySource(IndexType.COLLECTION, COLLECTION, SOURCE) .process(cluster.getSolrClient()); assertEquals( List.of( - Map.of("source", SOURCE, "dest", DEST_ONE, "maxChars", 100), - Map.of("source", SOURCE, "dest", DEST_TWO, "maxChars", 20)), + Map.of("source", SOURCE, "destination", DEST_ONE, "maxChars", 100), + Map.of("source", SOURCE, "destination", DEST_TWO, "maxChars", 20)), response.copyFields); } @Test public void testPutChangesLimitsAndSupportsUnlimitedDestination() throws Exception { - putCopyFields(SOURCE, List.of(Map.of("dest", DEST_ONE, "maxChars", 100))); + putCopyFields(SOURCE, List.of(Map.of("destination", DEST_ONE, "maxChars", 100))); putCopyFields( - SOURCE, List.of(Map.of("dest", DEST_ONE, "maxChars", 20), Map.of("dest", DEST_TWO))); + SOURCE, + List.of(Map.of("destination", DEST_ONE, "maxChars", 20), Map.of("destination", DEST_TWO))); var response = new SchemaApi.ListCopyFieldsBySource(IndexType.COLLECTION, COLLECTION, SOURCE) .process(cluster.getSolrClient()); assertEquals( List.of( - Map.of("source", SOURCE, "dest", DEST_ONE, "maxChars", 20), - Map.of("source", SOURCE, "dest", DEST_TWO)), + Map.of("source", SOURCE, "destination", DEST_ONE, "maxChars", 20), + Map.of("source", SOURCE, "destination", DEST_TWO)), response.copyFields); } @Test public void testFailedMultiDestinationPutAndPostAreAtomic() throws Exception { - putCopyFields(SOURCE, List.of(Map.of("dest", DEST_ONE, "maxChars", 100))); + putCopyFields(SOURCE, List.of(Map.of("destination", DEST_ONE, "maxChars", 100))); var invalidRules = List.of( - Map.of("dest", DEST_TWO, "maxChars", 20), Map.of("dest", "no_such_destination_field")); + Map.of("destination", DEST_TWO, "maxChars", 20), + Map.of("destination", "no_such_destination_field")); expectThrows(RemoteSolrException.class, () -> putCopyFields(SOURCE, invalidRules)); expectThrows(RemoteSolrException.class, () -> postCopyFields(SOURCE, invalidRules)); var response = new SchemaApi.ListCopyFieldsBySource(IndexType.COLLECTION, COLLECTION, SOURCE) .process(cluster.getSolrClient()); assertEquals( - List.of(Map.of("source", SOURCE, "dest", DEST_ONE, "maxChars", 100)), response.copyFields); + List.of(Map.of("source", SOURCE, "destination", DEST_ONE, "maxChars", 100)), + response.copyFields); } @Test @@ -218,9 +228,9 @@ public void testInvalidDestinationListsLeaveRulesIntact() throws Exception { nullRule.add(null); for (Object invalid : List.of( - List.of(Map.of("dest", DEST_TWO, "maxChars", -1)), - List.of(Map.of("dest", "")), - List.of(Map.of("dest", " ")), + List.of(Map.of("destination", DEST_TWO, "maxChars", -1)), + List.of(Map.of("destination", "")), + List.of(Map.of("destination", " ")), rules(DEST_TWO, DEST_TWO), nullRule, List.of(Map.of("maxChars", 10)), @@ -235,6 +245,45 @@ public void testInvalidDestinationListsLeaveRulesIntact() throws Exception { } } + @Test + @SuppressWarnings("unchecked") + public void testV2SchemaReadsUseDestinationAndV1RetainsDest() throws Exception { + new SchemaRequest.AddCopyField(SOURCE, List.of(DEST_ONE, DEST_TWO), 100) + .process(cluster.getSolrClient(), COLLECTION); + var v2Schema = + new SchemaApi.GetSchemaInfo(IndexType.COLLECTION, COLLECTION) + .process(cluster.getSolrClient()); + var v2Rules = (List>) v2Schema.schema.get("copyFields"); + assertTrue( + v2Rules.stream() + .allMatch(rule -> rule.containsKey("destination") && !rule.containsKey("dest"))); + var v1Schema = new SchemaRequest().process(cluster.getSolrClient(), COLLECTION); + var v1Rules = + (List>) + ((Map) v1Schema.getResponse().get("schema")).get("copyFields"); + assertTrue( + v1Rules.stream() + .allMatch(rule -> rule.containsKey("dest") && !rule.containsKey("destination"))); + var v2Filtered = + new V2Request.Builder(schemaPath("/copyfields")) + .GET() + .withParams(params("source.fl", SOURCE, "destination.fl", DEST_TWO)) + .build() + .process(cluster.getSolrClient()); + assertEquals( + List.of(Map.of("source", SOURCE, "destination", DEST_TWO, "maxChars", 100)), + v2Filtered.getResponse().get("copyFields")); + var v1Filtered = + new SchemaRequest.CopyFields(params("source.fl", SOURCE, "dest.fl", DEST_TWO)) + .process(cluster.getSolrClient(), COLLECTION); + assertEquals( + List.of(Map.of("source", SOURCE, "dest", DEST_TWO, "maxChars", 100)), + v1Filtered.getCopyFields()); + new SchemaRequest.DeleteCopyField(SOURCE, List.of(DEST_ONE, DEST_TWO)) + .process(cluster.getSolrClient(), COLLECTION); + assertEquals(List.of(), destinationsOf(SOURCE)); + } + @Test public void testV1StillAcceptsScalarDest() throws Exception { var request = @@ -256,6 +305,58 @@ public void testV1StillAcceptsScalarDest() throws Exception { .getCopyFields()); } + @Test + public void testV2BulkUsesOneDestinationPerOperation() throws Exception { + var bulk = new SchemaApi.BulkSchemaModification(IndexType.COLLECTION, COLLECTION); + for (var rule : List.of(destination(DEST_ONE, 100), destination(DEST_TWO, 20))) { + var add = new AddCopyFieldRequest(); + add.operationType = "add-copy-field"; + add.source = SOURCE; + add.destination = rule.destination; + add.maxChars = rule.maxChars; + bulk.addSchemaChange(add); + } + bulk.process(cluster.getSolrClient()); + var response = + new SchemaApi.ListCopyFieldsBySource(IndexType.COLLECTION, COLLECTION, SOURCE) + .process(cluster.getSolrClient()); + assertEquals( + List.of( + Map.of("source", SOURCE, "destination", DEST_ONE, "maxChars", 100), + Map.of("source", SOURCE, "destination", DEST_TWO, "maxChars", 20)), + response.copyFields); + var delete = new DeleteCopyFieldRequest(); + delete.operationType = "delete-copy-field"; + delete.source = SOURCE; + delete.destination = DEST_ONE; + var deleteBulk = new SchemaApi.BulkSchemaModification(IndexType.COLLECTION, COLLECTION); + deleteBulk.addSchemaChange(delete); + deleteBulk.process(cluster.getSolrClient()); + assertEquals(List.of(DEST_TWO), destinationsOf(SOURCE)); + for (String legacyName : List.of("dest", "destinations")) { + assertEquals( + 400, + expectThrows( + RemoteSolrException.class, + () -> + new V2Request.Builder(schemaPath("/bulk")) + .POST() + .withPayload( + List.of( + Map.of( + "operationType", + "add-copy-field", + "source", + SOURCE, + legacyName, + DEST_ONE))) + .build() + .process(cluster.getSolrClient())) + .code()); + } + assertEquals(List.of(DEST_TWO), destinationsOf(SOURCE)); + } + @Test public void testDynamicSourceSupportsIndividualLimits() throws Exception { String source = "*_s"; @@ -263,21 +364,22 @@ public void testDynamicSourceSupportsIndividualLimits() throws Exception { putCopyFields( source, List.of( - Map.of("dest", DEST_ONE, "maxChars", 100), Map.of("dest", DEST_TWO, "maxChars", 20))); + Map.of("destination", DEST_ONE, "maxChars", 100), + Map.of("destination", DEST_TWO, "maxChars", 20))); var response = new SchemaApi.ListCopyFieldsBySource(IndexType.COLLECTION, COLLECTION, source) .process(cluster.getSolrClient()); assertEquals( List.of( - Map.of("source", source, "dest", DEST_ONE, "maxChars", 100), - Map.of("source", source, "dest", DEST_TWO, "maxChars", 20)), + Map.of("source", source, "destination", DEST_ONE, "maxChars", 100), + Map.of("source", source, "destination", DEST_TWO, "maxChars", 20)), response.copyFields); - putCopyFields(source, List.of(Map.of("dest", DEST_TWO, "maxChars", 0))); + putCopyFields(source, List.of(Map.of("destination", DEST_TWO, "maxChars", 0))); postCopyFields(source, List.of()); response = new SchemaApi.ListCopyFieldsBySource(IndexType.COLLECTION, COLLECTION, source) .process(cluster.getSolrClient()); - assertEquals(List.of(Map.of("source", source, "dest", DEST_TWO)), response.copyFields); + assertEquals(List.of(Map.of("source", source, "destination", DEST_TWO)), response.copyFields); } finally { putCopyFields(source, List.of()); } @@ -302,7 +404,8 @@ public void testGeneratedPutReplacesCopyFields() throws Exception { new SchemaApi.ListCopyFieldsBySource(IndexType.COLLECTION, COLLECTION, SOURCE) .process(cluster.getSolrClient()); assertEquals( - List.of(Map.of("source", SOURCE, "dest", DEST_TWO, "maxChars", 100)), response.copyFields); + List.of(Map.of("source", SOURCE, "destination", DEST_TWO, "maxChars", 100)), + response.copyFields); } @Test @@ -318,8 +421,8 @@ public void testGeneratedPostAppendsCopyFields() throws Exception { .process(cluster.getSolrClient()); assertEquals( List.of( - Map.of("source", SOURCE, "dest", DEST_ONE), - Map.of("source", SOURCE, "dest", DEST_TWO, "maxChars", 100)), + Map.of("source", SOURCE, "destination", DEST_ONE), + Map.of("source", SOURCE, "destination", DEST_TWO, "maxChars", 100)), response.copyFields); } @@ -369,7 +472,7 @@ public void testFailedPutLeavesExistingRulesIntact() throws Exception { @Test public void testAddAcceptsSingleDestinationAndMaxChars() throws Exception { - putCopyFields(SOURCE, List.of(Map.of("dest", DEST_ONE, "maxChars", 100))); + putCopyFields(SOURCE, List.of(Map.of("destination", DEST_ONE, "maxChars", 100))); assertEquals(List.of(DEST_ONE), destinationsOf(SOURCE)); } @@ -515,8 +618,8 @@ public void testBulkDeleteOfMissingRuleIsBadRequest() throws Exception { "delete-copy-field", "source", SOURCE, - "destinations", - List.of(DEST_TWO)))) + "destination", + DEST_TWO))) .build() .process(cluster.getSolrClient())); @@ -562,6 +665,16 @@ public void testDeleteRejectsAPathSegmentNamingNoDestinations() throws Exception assertEquals(List.of(DEST_ONE), destinationsOf(SOURCE)); } + @Test + public void testV2RejectsLegacyDestinationName() { + final var thrown = + expectThrows( + RemoteSolrException.class, + () -> putCopyFields(SOURCE, List.of(Map.of("dest", DEST_ONE)))); + + assertEquals(400, thrown.code()); + } + @Test public void testAddRequiresDestinations() throws Exception { final var thrown = @@ -570,6 +683,7 @@ public void testAddRequiresDestinations() throws Exception { () -> putCopyFields(SOURCE, List.of(Map.of("maxChars", 100)))); assertEquals(400, thrown.code()); - assertTrue("unexpected message: " + thrown.getMessage(), thrown.getMessage().contains("dest")); + assertTrue( + "unexpected message: " + thrown.getMessage(), thrown.getMessage().contains("destination")); } } diff --git a/solr/core/src/test/org/apache/solr/handler/admin/api/V2UpdateSchemaErrorCaseTests.java b/solr/core/src/test/org/apache/solr/handler/admin/api/V2UpdateSchemaErrorCaseTests.java index 391e5126e767..426eeef81822 100644 --- a/solr/core/src/test/org/apache/solr/handler/admin/api/V2UpdateSchemaErrorCaseTests.java +++ b/solr/core/src/test/org/apache/solr/handler/admin/api/V2UpdateSchemaErrorCaseTests.java @@ -161,7 +161,7 @@ public void testDeleteFieldTypeOperationRequiresTypeName() { @Test public void testUpsertCopyFieldsOperationRequiresSourceAndDestinations() { final var noSourceOp = new CopyFieldDestination(); - noSourceOp.dest = "someDestination"; + noSourceOp.destination = "someDestination"; var thrown = expectThrows( SolrException.class, @@ -179,7 +179,7 @@ public void testUpsertCopyFieldsOperationRequiresSourceAndDestinations() { schemaApi.upsertCopyFields("someSourceField", List.of(noDestinationsOp)); }); assertEquals(BAD_REQUEST.code, thrown.code()); - assertThat(thrown.getMessage(), containsString("Missing required parameter: dest")); + assertThat(thrown.getMessage(), containsString("Missing required parameter: destination")); } @Test diff --git a/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc b/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc index 4233772a2ec2..72d98c052658 100644 --- a/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc +++ b/solr/solr-ref-guide/modules/indexing-guide/pages/schema-api.adoc @@ -495,7 +495,7 @@ s|Required |Default: none |=== + A field or an array of fields to which the source field will be copied. -V2 per-source writes use one `dest` per rule, as shown below. +The v2 API uses one `destination` per rule, as shown below. `maxChars`:: + @@ -531,8 +531,8 @@ V2 API:: ---- curl -X PUT -H 'Content-type:application/json' --data-binary ' [ - { "dest": "location", "maxChars": 100 }, - { "dest": "catchall", "maxChars": 20 } + { "destination": "location", "maxChars": 100 }, + { "destination": "catchall", "maxChars": 20 } ]' http://localhost:8983/api/collections/techproducts/schema/copyfields/shelf ---- ==== @@ -540,9 +540,9 @@ curl -X PUT -H 'Content-type:application/json' --data-binary ' + Copy-field rules have no name of their own, so v2 addresses them by their source field: the source is the final path segment, and the body carries the destinations. -The body is an array of objects, each with a required `dest` and an optional `maxChars`. +The body is an array of objects, each with a required `destination` and an optional `maxChars`. Each destination can have a different limit; omitting `maxChars` or setting it to `0` copies all characters. -Each destination must appear only once in the array. +The v2 API does not accept `dest` or `destinations` as aliases, and each destination must appear only once in the array. + [IMPORTANT] ==== @@ -558,7 +558,7 @@ To add destinations while leaving the source's existing rules alone, `POST` to t ---- curl -X POST -H 'Content-type:application/json' --data-binary ' [ - { "dest": "catchall", "maxChars": 20 } + { "destination": "catchall", "maxChars": 20 } ]' http://localhost:8983/api/collections/techproducts/schema/copyfields/shelf ---- + @@ -683,7 +683,8 @@ curl 'http://localhost:8983/solr/techproducts/schema' -H 'Content-type:applicati Bulk schema operations are also supported in Solr's v2 API, using a different endpoint and syntax. The v2 bulk endpoint is `POST /api/collections/_collection_/schema/bulk`; the `/schema` path itself only supports `GET` in v2. -Individual operations are specified as elements within a list, with the operation name (e.g. `add-field`, `delete-field-type`) specified as a `"operationType"` property on each operation object: +Individual operations are specified as elements within a list, with the operation name (e.g. `add-field`, `delete-field-type`) specified as a `"operationType"` property on each operation object. +The v2 `add-copy-field` and `delete-copy-field` operations each name one `source` and one `destination`; repeat the operation to address several destinations: [source,bash] ---- @@ -704,7 +705,14 @@ curl 'http://localhost:8983/api/collections/techproducts/schema/bulk' -H 'Conten { "operationType": "add-copy-field", "source": "shelf", - "destinations": ["location", "catchall"] + "destination": "location", + "maxChars": 100 + }, + { + "operationType": "add-copy-field", + "source": "shelf", + "destination": "catchall", + "maxChars": 20 } ]' ---- @@ -1366,7 +1374,7 @@ Comma- or space-separated list of one or more copyField source fields to include CopyField directives with all other source fields will be excluded from the response. If not specified, all copyField-s will be included in the response. -`dest.fl`:: +`dest.fl` (v1), `destination.fl` (v2):: + [%autowidth,frame=none] |=== @@ -1379,7 +1387,9 @@ If not specified, all copyField-s will be included in the response. ==== List Copy Field Response -The output will include the `source` and `dest` (destination) of each copy field rule defined in `schema.xml`. +The output includes the `source` and destination of each copy field rule defined in `schema.xml`. +V1 names the destination `dest`; v2 names it `destination`, including in the full schema response. +For dynamic rules, v2 also uses `destinationDynamicBase` in place of `destDynamicBase`. For more information about copy fields, see the section xref:copy-fields.adoc[]. ==== List Copy Field Examples @@ -1407,7 +1417,8 @@ curl 'http://localhost:8983/api/collections/techproducts/schema/copyfields' ==== ====== -The sample output below has been truncated to the first few copy definitions. +The v1 sample output below has been truncated to the first few copy definitions. +V2 returns the same structure using `destination` in place of `dest`. [source,json] ---- diff --git a/solr/solr-ref-guide/modules/upgrade-notes/pages/major-changes-in-solr-11.adoc b/solr/solr-ref-guide/modules/upgrade-notes/pages/major-changes-in-solr-11.adoc index 184aee185213..c5ee1e7900d3 100644 --- a/solr/solr-ref-guide/modules/upgrade-notes/pages/major-changes-in-solr-11.adoc +++ b/solr/solr-ref-guide/modules/upgrade-notes/pages/major-changes-in-solr-11.adoc @@ -25,6 +25,14 @@ This page highlights the most important changes including new features and chang Before starting an upgrade to this version of Solr, please be sure to review all information about changes from the version you are currently on up to this one, to include the minor version number changes as well. For example, if you are currently using Solr 10.1, you should review changes made in all subsequent 10.x releases in addition to the 11.0-specific changes on this page. +== Schema API + +V2 copy-field rules use `destination` instead of `dest` in reads and bulk operations, and `destination.fl` instead of `dest.fl` for filtering. +Per-source `PUT` and `POST` requests take an array of objects containing `destination` and an optional `maxChars`, allowing a different character limit for each destination. +V2 bulk copy-field operations each address one destination. +The v1 Schema API retains its existing request and response formats. +See xref:indexing-guide:schema-api.adoc[] for examples. + == Removed Features === Overseer Roles API diff --git a/solr/webapp/web/js/angular/controllers/schema.js b/solr/webapp/web/js/angular/controllers/schema.js index 6480d62e11b7..21946a447fc2 100644 --- a/solr/webapp/web/js/angular/controllers/schema.js +++ b/solr/webapp/web/js/angular/controllers/schema.js @@ -291,7 +291,7 @@ solrAdminApp.controller('SchemaController', return; } var indexType = $scope.isCloudEnabled ? "collections" : "cores"; - var rule = {dest: $scope.copyField.dest}; + var rule = {destination: $scope.copyField.dest}; if ($scope.copyField.maxChars != null) { rule.maxChars = $scope.copyField.maxChars; }