Skip to content
Open
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions changelog/unreleased/SOLR-18479-v2-copyfield-api.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
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 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
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.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;
Expand Down Expand Up @@ -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
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, with a character limit per destination. 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(required = true) List<CopyFieldDestination> 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<CopyFieldDestination> 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
@@ -0,0 +1,27 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.client.api.model;

import com.fasterxml.jackson.annotation.JsonProperty;

/** A destination and its optional character limit for a v2 copy-field rule. */
public class CopyFieldDestination {
@JsonProperty(required = true)
public String dest;

@JsonProperty public Integer maxChars;
}
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/{dynamicFieldName}
* <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
145 changes: 145 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,23 @@
*/
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.CopyFieldDestination;
import org.apache.solr.client.api.model.DeleteCopyFieldOperation;
import org.apache.solr.client.api.model.DeleteDynamicFieldOperation;
import org.apache.solr.client.api.model.DeleteFieldOperation;
import org.apache.solr.client.api.model.DeleteFieldTypeOperation;
Expand All @@ -39,6 +47,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 +160,142 @@ public SolrJerseyResponse deleteFieldType(String fieldTypeName) throws Exception
return response;
}

@Override
@PermissionName(PermissionNameProvider.Name.SCHEMA_EDIT_PERM)
public SolrJerseyResponse upsertCopyFields(
String sourceField, List<CopyFieldDestination> requestBody) throws Exception {
return runCopyFieldOperation(sourceField, requestBody, "upsert-copy-field");
}

@Override
@PermissionName(PermissionNameProvider.Name.SCHEMA_EDIT_PERM)
public SolrJerseyResponse appendCopyFields(
String sourceField, List<CopyFieldDestination> 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, List<CopyFieldDestination> requestBody, String operationType)
throws Exception {
final var response = instantiateJerseyResponse(SolrJerseyResponse.class);
ensureSchemaMutable();
ensureRequiredParameterProvided("sourceField", sourceField);
ensureRequiredRequestBodyProvided(requestBody);
final List<SchemaChange> 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<String>();
for (CopyFieldDestination rule : requestBody) {
ensureRequiredParameterProvided("dest", rule == null ? null : rule.dest);
if (!destinations.add(rule.dest)) {
throw new SolrException(
SolrException.ErrorCode.BAD_REQUEST, "Duplicate destination: " + rule.dest);
}
final var add = copyFieldOperation(sourceField, rule.dest, rule.maxChars);
add.operationType =
operationType.equals("upsert-copy-field") ? "add-copy-field" : operationType;
operations.add(add);
}
runWithSchemaManager(operations);

return response;
}

@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<String> 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("dest", destination);
if (destination.isBlank()) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "destination must not be blank");
}
if (maxChars != null && maxChars < 0) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "maxChars must not be negative");
}
final var operation = new AddCopyFieldOperation();
operation.source = source;
operation.destinations = List.of(destination);
operation.maxChars = maxChars;
operation.operationType = "add-copy-field";
return operation;
}

/**
* 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
14 changes: 10 additions & 4 deletions solr/core/src/java/org/apache/solr/schema/ManagedIndexSchema.java
Original file line number Diff line number Diff line change
Expand Up @@ -892,8 +892,14 @@ public ManagedIndexSchema addCopyFields(
}

@Override
@SuppressWarnings({"unchecked"})
public ManagedIndexSchema deleteCopyFields(Map<String, Collection<String>> 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<String, Collection<String>> copyFields, ErrorCode missingRuleErrorCode) {
ManagedIndexSchema newSchema;
if (isMutable) {
newSchema = shallowCopy(true);
Expand All @@ -909,7 +915,7 @@ public ManagedIndexSchema deleteCopyFields(Map<String, Collection<String>> copyF
for (Map.Entry<String, Collection<String>> 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();
Expand All @@ -922,7 +928,7 @@ public ManagedIndexSchema deleteCopyFields(Map<String, Collection<String>> 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);
Expand Down Expand Up @@ -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 + "'");
}
}
Expand Down
Loading
Loading