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..b182cdd8c8ab --- /dev/null +++ b/changelog/unreleased/SOLR-18479-v2-copyfield-api.yml @@ -0,0 +1,17 @@ +title: > + 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: `GET` lists that source's rules, `PUT` sets its + 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. +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/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/endpoint/GetSchemaApi.java b/solr/api/src/java/org/apache/solr/client/api/endpoint/GetSchemaApi.java index a42f832b154f..13f9529ea5f8 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 5b5971928f3d..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,6 +29,7 @@ import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import java.util.List; +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; @@ -112,25 +113,56 @@ 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 = + "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) List 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(required = true) List 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 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 deleteCopyFieldsByDestination( + @PathParam("sourceField") String sourceField, + @PathParam("destinationFields") String destinationFields) + throws Exception; @POST @Path("/bulk") 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 new file mode 100644 index 000000000000..5560b5faa703 --- /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 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 e19b08fc325e..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,8 +18,10 @@ 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; import org.apache.solr.api.JerseyResource; import org.apache.solr.client.api.endpoint.GetSchemaApi; import org.apache.solr.client.api.model.SchemaGetDynamicFieldInfoResponse; @@ -32,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; @@ -48,6 +51,7 @@ *
  • /fields *
  • /fields/{fieldName} *
  • /copyfields + *
  • /copyfields/{sourceField} *
  • /dynamicfields *
  • /dynamicfields/{dynamicFieldName} *
  • /fieldtypes @@ -99,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"; @@ -108,6 +128,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 = + copyFieldsForV2(indexSchema.getCopyFieldProperties(false, Set.of(sourceField), null)); + + return response; + } + @Override @PermissionName(PermissionNameProvider.Name.SCHEMA_READ_PERM) public SchemaListDynamicFieldsResponse listDynamicFields() { @@ -175,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 55b66b4bed5e..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 @@ -16,15 +16,25 @@ */ 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; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; 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.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; @@ -39,6 +49,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 +162,142 @@ public SolrJerseyResponse deleteFieldType(String fieldTypeName) throws Exception return response; } + @Override + @PermissionName(PermissionNameProvider.Name.SCHEMA_EDIT_PERM) + 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, List 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, List requestBody, String operationType) + throws Exception { + final var response = instantiateJerseyResponse(SolrJerseyResponse.class); + ensureSchemaMutable(); + ensureRequiredParameterProvided("sourceField", sourceField); + ensureRequiredRequestBodyProvided(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("destination", rule == null ? null : rule.destination); + if (!destinations.add(rule.destination)) { + throw new SolrException( + SolrException.ErrorCode.BAD_REQUEST, "Duplicate destination: " + rule.destination); + } + final var add = copyFieldOperation(sourceField, rule.destination, rule.maxChars); + add.operationType = + operationType.equals("upsert-copy-field") ? "add-copy-field" : operationType; + operations.add(add); + } + runWithSchemaManager(operations); + + return response; + } + + @Override + @PermissionName(PermissionNameProvider.Name.SCHEMA_EDIT_PERM) + public SolrJerseyResponse deleteCopyFields(String sourceField) throws Exception { + ensureSchemaMutable(); + ensureRequiredParameterProvided("sourceField", 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. + return runCopyFieldOperation(sourceField, List.of(), "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. + final var destinations = + 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); + + final var deleteCopyFieldOp = new DeleteCopyFieldOperation(); + deleteCopyFieldOp.operationType = "delete-copy-field-by-destination"; + deleteCopyFieldOp.source = sourceField; + deleteCopyFieldOp.destinations = destinations; + + runWithSchemaManager(List.of(deleteCopyFieldOp)); + + return response; + } + + private AddCopyFieldOperation copyFieldOperation( + String source, String destination, Integer maxChars) { + ensureRequiredParameterProvided("source", source); + ensureRequiredParameterProvided("destination", 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; + } + + /** + * 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) @@ -159,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/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 2a6e53ceaadb..4368f163b2f4 100644 --- a/solr/core/src/java/org/apache/solr/schema/SchemaManager.java +++ b/solr/core/src/java/org/apache/solr/schema/SchemaManager.java @@ -296,6 +296,45 @@ 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 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"); @@ -345,6 +384,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 { @@ -432,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/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 new file mode 100644 index 000000000000..00da7098c665 --- /dev/null +++ b/solr/core/src/test/org/apache/solr/handler/admin/api/V2CopyFieldApiTest.java @@ -0,0 +1,689 @@ +/* + * 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.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.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; +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.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 { + // 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, 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("destination", destination)) + .toList(); + } + + private static CopyFieldDestination destination(String field, Integer maxChars) { + final var destination = new CopyFieldDestination(); + destination.destination = field; + destination.maxChars = maxChars; + return destination; + } + + private static void putCopyFields(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 suffix = destinations.length == 0 ? "" : "/" + String.join(",", destinations); + new V2Request.Builder(schemaPath("/copyfields/" + source + suffix)) + .DELETE() + .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("destination")).sorted().toList(); + } + + /** 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("destination")) + .sorted() + .collect(Collectors.toList()); + } + + @Test + public void testPutUsesIndividualDestinationLimits() throws Exception { + putCopyFields( + SOURCE, + List.of( + Map.of("destination", DEST_ONE, "maxChars", 100), + Map.of("destination", DEST_TWO, "maxChars", 20))); + + var response = + new V2Request.Builder(schemaPath("/copyfields/" + SOURCE)) + .GET() + .build() + .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.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("destination", DEST_ONE, "maxChars", 100))); + postCopyFields( + SOURCE, + 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, "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("destination", DEST_ONE, "maxChars", 100))); + putCopyFields( + 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, "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("destination", DEST_ONE, "maxChars", 100))); + var invalidRules = + List.of( + 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, "destination", 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("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)), + 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 + @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 = + 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 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"; + try { + putCopyFields( + source, + List.of( + 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, "destination", DEST_ONE, "maxChars", 100), + Map.of("source", source, "destination", DEST_TWO, "maxChars", 20)), + response.copyFields); + 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, "destination", DEST_TWO)), response.copyFields); + } finally { + putCopyFields(source, List.of()); + } + } + + @Test + public void testAddAndListCopyFieldsBySource() throws Exception { + putCopyFields(SOURCE, rules(DEST_ONE, DEST_TWO)); + + assertEquals(List.of(DEST_ONE, DEST_TWO), destinationsOf(SOURCE)); + } + + @Test + public void testGeneratedPutReplacesCopyFields() throws Exception { + putCopyFields(SOURCE, rules(DEST_ONE, DEST_TWO)); + + var request = new SchemaApi.UpsertCopyFields(IndexType.COLLECTION, COLLECTION, SOURCE); + request.addCopyFieldDestination(destination(DEST_TWO, 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, "destination", DEST_TWO, "maxChars", 100)), + response.copyFields); + } + + @Test + public void testGeneratedPostAppendsCopyFields() throws Exception { + putCopyFields(SOURCE, rules(DEST_ONE)); + + var request = new SchemaApi.AppendCopyFields(IndexType.COLLECTION, COLLECTION, SOURCE); + request.addCopyFieldDestination(destination(DEST_TWO, 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, "destination", DEST_ONE), + Map.of("source", SOURCE, "destination", DEST_TWO, "maxChars", 100)), + response.copyFields); + } + + @Test + public void testRepeatedPutIsIdempotent() throws Exception { + 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. + assertEquals(List.of(DEST_ONE, DEST_TWO), destinationsOf(SOURCE)); + } + + @Test + public void testPutReplacesTheSourcesExistingRules() throws Exception { + putCopyFields(SOURCE, rules(DEST_ONE, DEST_TWO)); + + putCopyFields(SOURCE, rules(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, rules(DEST_ONE)); + + putCopyFields(SOURCE, rules(DEST_ONE, DEST_TWO)); + + assertEquals(List.of(DEST_ONE, DEST_TWO), destinationsOf(SOURCE)); + } + + @Test + public void testFailedPutLeavesExistingRulesIntact() throws Exception { + putCopyFields(SOURCE, rules(DEST_ONE)); + + expectThrows( + RemoteSolrException.class, () -> putCopyFields(SOURCE, rules("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 { + putCopyFields(SOURCE, List.of(Map.of("destination", DEST_ONE, "maxChars", 100))); + + assertEquals(List.of(DEST_ONE), destinationsOf(SOURCE)); + } + + @Test + public void testDeleteNarrowedByDestinationParam() throws Exception { + putCopyFields(SOURCE, rules(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 { + putCopyFields(SOURCE, rules(DEST_ONE, DEST_TWO)); + + deleteCopyFields(SOURCE); + + assertEquals(List.of(), destinationsOf(SOURCE)); + } + + @Test + public void testDeleteLeavesRulesWithOtherSourcesAlone() throws Exception { + putCopyFields(SOURCE, rules(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 testGetBySourceReturnsOnlyThatSourcesDestinations() throws Exception { + putCopyFields(SOURCE, rules(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, rules(DEST_ONE)); + + postCopyFields(SOURCE, rules(DEST_TWO)); + + assertEquals(List.of(DEST_ONE, DEST_TWO), destinationsOf(SOURCE)); + } + + @Test + public void testPostSkipsDestinationsAlreadyPresent() throws Exception { + putCopyFields(SOURCE, rules(DEST_ONE)); + + 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)); + } + + @Test + public void testDeleteOfSeveralDestinationsInOnePathSegment() throws Exception { + putCopyFields(SOURCE, rules(DEST_ONE, DEST_TWO)); + + deleteCopyFields(SOURCE, DEST_ONE, DEST_TWO); + + assertEquals(List.of(), destinationsOf(SOURCE)); + } + + @Test + public void testDeleteOfMissingNamedRuleIsNotFound() throws Exception { + putCopyFields(SOURCE, rules(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, rules(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, rules(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, + "destination", + 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, rules(DEST_ONE, DEST_TWO)); + + putCopyFields(SOURCE, rules()); + + assertEquals(List.of(), destinationsOf(SOURCE)); + } + + @Test + public void testDeleteRejectsAPathSegmentNamingNoDestinations() throws Exception { + putCopyFields(SOURCE, rules(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 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 = + expectThrows( + RemoteSolrException.class, + () -> putCopyFields(SOURCE, List.of(Map.of("maxChars", 100)))); + + assertEquals(400, thrown.code()); + 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 d981f572a0b1..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 @@ -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.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; @@ -155,4 +157,40 @@ public void testDeleteFieldTypeOperationRequiresTypeName() { assertEquals(BAD_REQUEST.code, thrown.code()); assertThat(thrown.getMessage(), containsString("Missing required parameter: fieldTypeName")); } + + @Test + public void testUpsertCopyFieldsOperationRequiresSourceAndDestinations() { + final var noSourceOp = new CopyFieldDestination(); + noSourceOp.destination = "someDestination"; + var thrown = + expectThrows( + SolrException.class, + () -> { + schemaApi.upsertCopyFields(null, List.of(noSourceOp)); + }); + assertEquals(BAD_REQUEST.code, thrown.code()); + assertThat(thrown.getMessage(), containsString("Missing required parameter: sourceField")); + + final var noDestinationsOp = new CopyFieldDestination(); + thrown = + expectThrows( + SolrException.class, + () -> { + schemaApi.upsertCopyFields("someSourceField", List.of(noDestinationsOp)); + }); + assertEquals(BAD_REQUEST.code, thrown.code()); + assertThat(thrown.getMessage(), containsString("Missing required parameter: destination")); + } + + @Test + public void testDeleteCopyFieldOperationRequiresSource() { + var thrown = + expectThrows( + SolrException.class, + () -> { + 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 ec6a818f4c0e..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. -In the v2 API this attribute is named `destinations`; `dest` is still accepted as an alias. +The v2 API uses one `destination` per rule, as shown below. `maxChars`:: + @@ -529,16 +529,44 @@ V2 API:: ==== [source,bash] ---- -curl 'http://localhost:8983/api/collections/techproducts/schema/bulk' -H 'Content-type:application/json' -d '[ - { - "operationType":"add-copy-field", - "source":"shelf", - "destinations":[ "location", "catchall" ] - } -]' +curl -X PUT -H 'Content-type:application/json' --data-binary ' +[ + { "destination": "location", "maxChars": 100 }, + { "destination": "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 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. +The v2 API does not accept `dest` or `destinations` as aliases, and 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 array (`[]`) removes every rule with that source. +==== ++ +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 ' +[ + { "destination": "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 @@ -567,12 +595,21 @@ V2 API:: ==== [source,bash] ---- -curl 'http://localhost:8983/api/collections/techproducts/schema/bulk' -H 'Content-type:application/json' --data-binary '[ - { "operationType":"delete-copy-field", "source":"shelf", "destinations":[ "location" ] } -]' +curl -X DELETE "http://localhost:8983/api/collections/techproducts/schema/copyfields/shelf/location" ---- ==== ====== ++ +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, or naming a rule that does not exist, returns a 404. === Multiple Commands in a Single POST @@ -646,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] ---- @@ -667,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 } ]' ---- @@ -1279,6 +1324,18 @@ 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. +A source with no copy-field rules returns an empty list rather than a 404. + ==== List Copy Field Parameters *Path Parameters* @@ -1317,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] |=== @@ -1330,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 @@ -1358,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/src/test/org/apache/solr/webapp/AdminUiSchemaScreenTest.java b/solr/webapp/src/test/org/apache/solr/webapp/AdminUiSchemaScreenTest.java index 372a38bdd336..40347d15b608 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,113 @@ public void testAddAndDeleteFieldViaUi() throws Exception { assertNoSevereConsoleErrors(); } + @Test + public void testCopyFieldsUseDedicatedEndpoints() throws Exception { + 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()']")); + + 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); + 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); + 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..21946a447fc2 100644 --- a/solr/webapp/web/js/angular/controllers/schema.js +++ b/solr/webapp/web/js/angular/controllers/schema.js @@ -286,14 +286,17 @@ 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) { + var rule = {destination: $scope.copyField.dest}; + if ($scope.copyField.maxChars != null) { + rule.maxChars = $scope.copyField.maxChars; + } + SchemaV2.appendCopyFields(indexType, $routeParams.core, $scope.copyField.source, + [rule], function(error, data, response) { $timeout(function() { if (error || (data && data.error)) { if (response && (response.status === 401 || response.status === 403)) { @@ -345,12 +348,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)) { 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}}

    - +