Skip to content
Open
14 changes: 14 additions & 0 deletions changelog/unreleased/SOLR-18479-v2-copyfield-api.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
title: >
The v2 Schema API can now manage copy-field rules directly, under
`/api/collections/<collection>/schema/copyfields/<sourceField>`.
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,
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
links:
- name: SOLR-18479
url: https://issues.apache.org/jira/browse/SOLR-18479
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.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;
Expand Down Expand Up @@ -112,25 +113,54 @@ 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
Comment thread
epugh marked this conversation as resolved.
Resolved
// /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. The given destinations "
+ "replace any rules that source already has.",
Comment thread
epugh marked this conversation as resolved.
Resolved
tags = {"schema"})
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 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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -48,6 +49,7 @@
* <li>/fields
* <li>/fields/{fieldName}
* <li>/copyfields
* <li>/copyfields/{sourceField}
* <li>/dynamicfields
* <li>/dynamicfields/{fieldName}
* <li>/fieldtypes
Expand Down Expand Up @@ -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() {
Expand Down
125 changes: 125 additions & 0 deletions solr/core/src/java/org/apache/solr/handler/admin/api/UpdateSchema.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,20 @@
*/
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.Arrays;
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;
Expand All @@ -39,6 +44,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;

Expand Down Expand Up @@ -151,6 +157,125 @@ public SolrJerseyResponse deleteFieldType(String fieldTypeName) throws Exception
return response;
}

@Override
@PermissionName(PermissionNameProvider.Name.SCHEMA_EDIT_PERM)
public SolrJerseyResponse upsertCopyFields(String sourceField, AddCopyFieldOperation 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 {
return runCopyFieldOperation(sourceField, requestBody, "append-copy-field");
}

/**
* Runs one of the copy-field operations that diff against the current schema.
*
* <p>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);
ensureBodySourceAgreesWithPath(sourceField, requestBody.source);

requestBody.source = sourceField;
requestBody.operationType = operationType;

runWithSchemaManager(List.of(requestBody));

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.
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.
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<String> destinations)
throws Exception {
final var response = instantiateJerseyResponse(SolrJerseyResponse.class);

final var deleteCopyFieldOp = new DeleteCopyFieldOperation();
deleteCopyFieldOp.operationType = "delete-copy-field";
deleteCopyFieldOp.source = sourceField;
deleteCopyFieldOp.destinations = destinations;

runWithSchemaManager(List.of(deleteCopyFieldOp));

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.
*
* <p>Covers dynamic (i.e. glob) rules as well as explicit ones, since either may be addressed by
* source.
*/
private List<String> 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<SchemaChange> requestBody)
Expand Down
63 changes: 63 additions & 0 deletions solr/core/src/java/org/apache/solr/schema/SchemaManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,26 @@ public SchemaOperationException(String message) {
}
}

/**
* Destinations of the copy-field rules that the in-progress schema declares for the given source.
*
* <p>Covers dynamic (i.e. glob) rules as well as explicit ones.
*/
private List<String> 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<String> destinations) {
final var op = new DeleteCopyFieldOperation();
op.operationType = "delete-copy-field";
op.source = source;
op.destinations = destinations;
return op;
}

private static <T> T ensureNotNull(String name, T value) throws SchemaOperationException {
if (value == null) {
throw new SchemaOperationException("'" + name + "' is a required field");
Expand Down Expand Up @@ -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<String> 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 {
Expand Down
Loading
Loading