View Javadoc
1   /*
2    * Copyright (C) 2024 B3Partners B.V.
3    *
4    * SPDX-License-Identifier: MIT
5    */
6   package org.tailormap.api.solr;
7   
8   import static org.tailormap.api.scheduling.IndexTask.INDEX_KEY;
9   
10  import jakarta.validation.constraints.NotNull;
11  import jakarta.validation.constraints.Positive;
12  import java.io.IOException;
13  import java.lang.invoke.MethodHandles;
14  import java.math.BigDecimal;
15  import java.time.Duration;
16  import java.time.Instant;
17  import java.time.OffsetDateTime;
18  import java.time.ZoneId;
19  import java.util.ArrayList;
20  import java.util.HashMap;
21  import java.util.HashSet;
22  import java.util.List;
23  import java.util.Map;
24  import java.util.Set;
25  import java.util.UUID;
26  import java.util.function.Consumer;
27  import org.apache.solr.client.solrj.RemoteSolrException;
28  import org.apache.solr.client.solrj.SolrClient;
29  import org.apache.solr.client.solrj.SolrResponse;
30  import org.apache.solr.client.solrj.SolrServerException;
31  import org.apache.solr.client.solrj.request.SolrQuery;
32  import org.apache.solr.client.solrj.request.schema.FieldTypeDefinition;
33  import org.apache.solr.client.solrj.request.schema.SchemaRequest;
34  import org.apache.solr.client.solrj.response.QueryResponse;
35  import org.apache.solr.client.solrj.response.UpdateResponse;
36  import org.apache.solr.client.solrj.response.schema.SchemaResponse;
37  import org.apache.solr.common.SolrDocumentList;
38  import org.apache.solr.common.SolrException;
39  import org.geotools.api.data.Query;
40  import org.geotools.api.data.SimpleFeatureSource;
41  import org.geotools.api.feature.simple.SimpleFeature;
42  import org.geotools.api.referencing.FactoryException;
43  import org.geotools.api.referencing.operation.MathTransform;
44  import org.geotools.data.simple.SimpleFeatureCollection;
45  import org.geotools.data.simple.SimpleFeatureIterator;
46  import org.jspecify.annotations.NonNull;
47  import org.jspecify.annotations.Nullable;
48  import org.locationtech.jts.geom.Geometry;
49  import org.slf4j.Logger;
50  import org.slf4j.LoggerFactory;
51  import org.tailormap.api.admin.model.SearchIndexSummary;
52  import org.tailormap.api.admin.model.TaskProgressEvent;
53  import org.tailormap.api.geotools.TransformationUtil;
54  import org.tailormap.api.geotools.featuresources.FeatureSourceFactoryHelper;
55  import org.tailormap.api.geotools.processing.GeometryProcessor;
56  import org.tailormap.api.geotools.wfs.WFSHitsCountUtil;
57  import org.tailormap.api.persistence.SearchIndex;
58  import org.tailormap.api.persistence.TMFeatureType;
59  import org.tailormap.api.persistence.helper.GeoToolsHelper;
60  import org.tailormap.api.repository.SearchIndexRepository;
61  import org.tailormap.api.scheduling.TaskType;
62  import org.tailormap.api.util.Constants;
63  import org.tailormap.api.viewer.model.SearchDocument;
64  import org.tailormap.api.viewer.model.SearchResponse;
65  
66  /**
67   * Solr utility/wrapper class. This class provides methods to add or update a full-text feature type index for a layer,
68   * find in the index for a layer, and clear the index for a layer. It also provides a method to close the Solr client as
69   * well as automatically closing the client when used in a try-with-resources.
70   */
71  public class SolrHelper implements AutoCloseable, Constants {
72    private static final Logger logger =
73        LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
74  
75    /** the Solr field type name geometry fields: {@value #SOLR_SPATIAL_FIELDNAME}. */
76    private static final String SOLR_SPATIAL_FIELDNAME = "tm_geometry_rpt";
77  
78    private final SolrClient solrClient;
79  
80    /** the Solr search field definition requests for Tailormap. */
81    private final Map<String, SchemaRequest.AddField> solrSearchFields = Map.of(
82        SEARCH_LAYER,
83            new SchemaRequest.AddField(Map.of(
84                "name", SEARCH_LAYER,
85                "type", "string",
86                "indexed", true,
87                "stored", true,
88                "multiValued", false,
89                "required", true,
90                "uninvertible", false)),
91        INDEX_GEOM_FIELD,
92            new SchemaRequest.AddField(
93                Map.of("name", INDEX_GEOM_FIELD, "type", SOLR_SPATIAL_FIELDNAME, "stored", true)),
94        INDEX_SEARCH_FIELD,
95            new SchemaRequest.AddField(Map.of(
96                "name", INDEX_SEARCH_FIELD,
97                "type", "text_general",
98                "indexed", true,
99                "stored", true,
100               "multiValued", true,
101               "required", true,
102               "uninvertible", false)),
103       INDEX_DISPLAY_FIELD,
104           new SchemaRequest.AddField(Map.of(
105               "name", INDEX_DISPLAY_FIELD,
106               "type", "text_general",
107               "indexed", false,
108               "stored", true,
109               "multiValued", true,
110               "required", true,
111               "uninvertible", false)));
112 
113   private int solrQueryTimeout = 7000;
114   private int solrBatchSize = 1000;
115   private String solrGeometryValidationRule = "repairBuffer0";
116 
117   /**
118    * Create a configured {@code SolrHelper} object.
119    *
120    * @param solrClient the Solr client, this will be closed when this class is closed
121    */
122   public SolrHelper(@NotNull SolrClient solrClient) {
123     this.solrClient = solrClient;
124   }
125 
126   /**
127    * Configure this {@code SolrHelper} with a query timeout .
128    *
129    * @param solrQueryTimeout the query timeout in seconds
130    */
131   public SolrHelper withQueryTimeout(
132       @Positive(message = "Must use a positive integer for query timeout") int solrQueryTimeout) {
133     this.solrQueryTimeout = solrQueryTimeout * 1000;
134     return this;
135   }
136 
137   /**
138    * Configure this {@code SolrHelper} with a batch size for submitting documents to the Solr instance.
139    *
140    * @param solrBatchSize the batch size for indexing, must be greater than 0
141    */
142   public SolrHelper withBatchSize(@Positive(message = "Must use a positive integer for batching") int solrBatchSize) {
143     this.solrBatchSize = solrBatchSize;
144     return this;
145   }
146 
147   /**
148    * Configure this {@code SolrHelper} to create a geometry field in Solr using the specified validation rule.
149    *
150    * @see <a
151    *     href="https://locationtech.github.io/spatial4j/apidocs/org/locationtech/spatial4j/context/jts/ValidationRule.html">ValidationRule</a>
152    * @param solrGeometryValidationRule any of {@code "error", "none", "repairBuffer0", "repairConvexHull"}
153    */
154   public SolrHelper withGeometryValidationRule(@NonNull String solrGeometryValidationRule) {
155     if (List.of("error", "none", "repairBuffer0", "repairConvexHull").contains(solrGeometryValidationRule)) {
156       logger.trace("Setting geometry validation rule for Solr geometry field to {}", solrGeometryValidationRule);
157       this.solrGeometryValidationRule = solrGeometryValidationRule;
158     }
159     return this;
160   }
161 
162   /**
163    * Add or update a feature type index for a layer.
164    *
165    * @param searchIndex the search index config
166    * @param tmFeatureType the feature type
167    * @param featureSourceFactoryHelper the feature source factory helper
168    * @param searchIndexRepository the search index repository, so we can save the {@code searchIndex}
169    * @throws IOException if an I/O error occurs
170    * @throws SolrServerException if a Solr error occurs
171    * @return the possibly updated {@code searchIndex} object
172    */
173   @SuppressWarnings("FromTemporalAccessor")
174   public SearchIndex addFeatureTypeIndex(
175       @NotNull SearchIndex searchIndex,
176       @NotNull TMFeatureType tmFeatureType,
177       @NotNull FeatureSourceFactoryHelper featureSourceFactoryHelper,
178       @NotNull SearchIndexRepository searchIndexRepository)
179       throws IOException, SolrServerException {
180     // use a dummy/logging listener when not given
181     Consumer<TaskProgressEvent> progressListener = (event) -> logger.debug("Progress event: {}", event);
182 
183     return this.addFeatureTypeIndex(
184         searchIndex, tmFeatureType, featureSourceFactoryHelper, searchIndexRepository, progressListener, null);
185   }
186 
187   /**
188    * Add or update a feature type index for a layer.
189    *
190    * @param searchIndex the search index config
191    * @param tmFeatureType the feature type
192    * @param featureSourceFactoryHelper the feature source factory helper
193    * @param searchIndexRepository the search index repository, so we can save the {@code searchIndex}
194    * @param progressListener the progress listener callback
195    * @param taskUuid the task UUID, when {@code null} we will attempt to use the UUID from the
196    *     {@code searchIndex#getSchedule()}
197    * @throws IOException if an I/O error occurs
198    * @throws SolrServerException if a Solr error occurs
199    * @return the possibly updated {@code searchIndex} object
200    */
201   @SuppressWarnings("FromTemporalAccessor")
202   public SearchIndex addFeatureTypeIndex(
203       @NotNull SearchIndex searchIndex,
204       @NotNull TMFeatureType tmFeatureType,
205       @NotNull FeatureSourceFactoryHelper featureSourceFactoryHelper,
206       @NotNull SearchIndexRepository searchIndexRepository,
207       @NotNull Consumer<TaskProgressEvent> progressListener,
208       @Nullable UUID taskUuid)
209       throws IOException, SolrServerException {
210 
211     createSchemaIfNotExists();
212 
213     final Instant startedAt = Instant.now();
214     final OffsetDateTime startedAtOffset =
215         startedAt.atOffset(ZoneId.systemDefault().getRules().getOffset(startedAt));
216 
217     if (null == taskUuid && null != searchIndex.getSchedule()) {
218       // this can be the case when this method is called directly such as when creating
219       // the test data. This in itself is not a big problem; it just means that the uuid
220       // in any progress events will be null (for that call).
221       taskUuid = searchIndex.getSchedule().getUuid();
222     }
223 
224     SearchIndexSummary summary =
225         new SearchIndexSummary().startedAt(startedAtOffset).total(0).duration(0.0);
226 
227     if (null == searchIndex.getSearchFieldsUsed()) {
228       logger.warn(
229           "No search fields configured for search index: {}, skipping index {}.",
230           tmFeatureType.getName(),
231           searchIndex.getName());
232       return searchIndexRepository.save(searchIndex
233           .setStatus(SearchIndex.Status.ERROR)
234           .setSummary(summary.errorMessage("No search fields configured")));
235     }
236 
237     TaskProgressEvent taskProgressEvent = new TaskProgressEvent()
238         .type(TaskType.INDEX.getValue())
239         .uuid(taskUuid)
240         .startedAt(startedAtOffset)
241         .progress(0)
242         .taskData(Map.of(INDEX_KEY, searchIndex.getId()));
243     progressListener.accept(taskProgressEvent);
244 
245     // set fields while filtering out hidden fields
246     List<String> searchFields = searchIndex.getSearchFieldsUsed().stream()
247         .filter(s -> !tmFeatureType.getSettings().getHideAttributes().contains(s))
248         .toList();
249     List<String> displayFields = searchIndex.getSearchDisplayFieldsUsed().stream()
250         .filter(s -> !tmFeatureType.getSettings().getHideAttributes().contains(s))
251         .toList();
252 
253     if (searchFields.isEmpty()) {
254       logger.warn(
255           "No valid search fields configured for feature type: {}, skipping index {}.",
256           tmFeatureType.getName(),
257           searchIndex.getName());
258       return searchIndexRepository.save(searchIndex
259           .setStatus(SearchIndex.Status.ERROR)
260           .setSummary(summary.errorMessage("No search fields configured")));
261     }
262 
263     // add search and display properties to query
264     Set<String> propertyNames = new HashSet<>();
265 
266     // always try to add primary key and default geometry to geotools query
267     if (null == tmFeatureType.getPrimaryKeyAttribute()) {
268       logger.error(
269           "No primary key attribute configured for feature type: {}, skipping index {}.",
270           tmFeatureType.getName(),
271           searchIndex.getName());
272       return searchIndexRepository.save(searchIndex
273           .setStatus(SearchIndex.Status.ERROR)
274           .setSummary(summary.errorMessage("No primary key attribute configured")));
275     }
276     propertyNames.add(tmFeatureType.getPrimaryKeyAttribute());
277     if (null == tmFeatureType.getDefaultGeometryAttribute()) {
278       logger.error(
279           "No default geometry attribute configured for feature type: {}, skipping index {}.",
280           tmFeatureType.getName(),
281           searchIndex.getName());
282       return searchIndexRepository.save(searchIndex
283           .setStatus(SearchIndex.Status.ERROR)
284           .setSummary(summary.errorMessage("No default geometry attribute configured")));
285     }
286     propertyNames.add(tmFeatureType.getDefaultGeometryAttribute());
287     propertyNames.addAll(searchFields);
288 
289     if (!displayFields.isEmpty()) {
290       propertyNames.addAll(displayFields);
291     }
292 
293     clearIndexForLayer(searchIndex.getId());
294 
295     logger.info("Indexing started for index: {}, feature type: {}", searchIndex.getName(), tmFeatureType.getName());
296     searchIndex = searchIndexRepository.save(searchIndex.setStatus(SearchIndex.Status.INDEXING));
297 
298     // null if unknown
299     final Integer total;
300     List<FeatureIndexingDocument> docsBatch = new ArrayList<>(solrBatchSize);
301     UpdateResponse updateResponse;
302     int indexCounter = 0;
303     int indexSkippedCounter = 0;
304 
305     // collect features to index
306     SimpleFeatureSource fs = featureSourceFactoryHelper.openGeoToolsFeatureSource(tmFeatureType);
307     // dispose the datastore on any return or exception after it has been opened
308     try {
309       Query q = new Query(fs.getName().toString());
310       // filter out any hidden properties (there should be none though)
311       tmFeatureType.getSettings().getHideAttributes().forEach(propertyNames::remove);
312       if (propertyNames.isEmpty()) {
313         logger.warn(
314             "No valid properties to index for feature type: {}, skipping index {}.",
315             tmFeatureType.getName(),
316             searchIndex.getName());
317         return searchIndexRepository.save(searchIndex
318             .setStatus(SearchIndex.Status.ERROR)
319             .setSummary(summary.errorMessage(
320                 "No valid properties to index. Check if any properties are hidden.")));
321       }
322       q.setPropertyNames(List.copyOf(propertyNames));
323       q.setStartIndex(0);
324       // TODO: make maxFeatures configurable?
325       // q.setMaxFeatures(Integer.MAX_VALUE);
326       logger.trace("Indexing query: {}", q);
327       SimpleFeatureCollection simpleFeatureCollection = fs.getFeatures(q);
328       int count = WFSHitsCountUtil.getCount(fs, q);
329       total = count >= 0 ? count : null;
330       // TODO this does not currently batch/page the feature source query, this doesn't seem to be an
331       //   issue for now but could be if the feature source is very, very large or slow
332       try (SimpleFeatureIterator iterator = simpleFeatureCollection.features()) {
333         searchIndex.setSourceCrs(
334             GeoToolsHelper.crsToString(fs.getSchema().getCoordinateReferenceSystem()));
335         while (iterator.hasNext()) {
336           indexCounter++;
337           SimpleFeature feature = iterator.next();
338           // note that this will create a unique document
339           FeatureIndexingDocument doc = new FeatureIndexingDocument(feature.getID(), searchIndex.getId());
340           List<String> searchValues = new ArrayList<>();
341           List<String> displayValues = new ArrayList<>();
342           propertyNames.forEach(propertyName -> {
343             Object value = feature.getAttribute(propertyName);
344             if (value != null) {
345               if (value instanceof Geometry
346                   && propertyName.equals(tmFeatureType.getDefaultGeometryAttribute())) {
347                 // We could use GeoJSON, but WKT is more compact and that would also incur a
348                 // change to the API
349                 doc.setGeometry(GeometryProcessor.processGeometry(value, true, true, null));
350               } else {
351                 if (searchFields.contains(propertyName)) {
352                   searchValues.add(value.toString());
353                 }
354                 if (displayFields.contains(propertyName)) {
355                   displayValues.add(value.toString());
356                 }
357               }
358             }
359           });
360           if (searchValues.isEmpty() || displayValues.isEmpty()) {
361             // this is a record/document that can either not be found or not be displayed
362             logger.trace(
363                 "No search or display values found for feature: {} in feature type: {}, skipped for indexing",
364                 feature.getID(),
365                 tmFeatureType.getName());
366             indexSkippedCounter++;
367           } else if (doc.getGeometry() == null || doc.getGeometry().matches("^[A-Z]+\\s*EMPTY\\s*$")) {
368             logger.trace(
369                 "No or empty geometry found for feature: {} in feature type: {}, skipped for indexing",
370                 feature.getID(),
371                 tmFeatureType.getName());
372             indexSkippedCounter++;
373           } else {
374             doc.setSearchFields(searchValues.toArray(new String[0]));
375             doc.setDisplayFields(displayValues.toArray(new String[0]));
376             docsBatch.add(doc);
377           }
378 
379           if (indexCounter % solrBatchSize == 0) {
380             updateResponse = solrClient.addBeans(docsBatch, solrQueryTimeout);
381             logger.info(
382                 "Added {} documents of {} to index, result status: {}",
383                 indexCounter - indexSkippedCounter,
384                 total,
385                 updateResponse.getStatus());
386             progressListener.accept(
387                 taskProgressEvent.total(total).progress((indexCounter - indexSkippedCounter)));
388             docsBatch.clear();
389           }
390         }
391       }
392     } finally {
393       if (fs.getDataStore() != null) fs.getDataStore().dispose();
394     }
395 
396     if (!docsBatch.isEmpty()) {
397       solrClient.addBeans(docsBatch, solrQueryTimeout);
398       logger.info("Added last {} documents of {} to index", docsBatch.size(), total);
399       progressListener.accept(taskProgressEvent
400           .progress((indexCounter - indexSkippedCounter))
401           .total(total));
402     }
403     final Instant finishedAt = Instant.now();
404     final OffsetDateTime finishedAtOffset =
405         finishedAt.atOffset(ZoneId.systemDefault().getRules().getOffset(finishedAt));
406     Duration processTime = Duration.between(startedAt, finishedAt).abs();
407     logger.info(
408         "Indexing finished for index: {}, feature type: {} at {} in {}",
409         searchIndex.getName(),
410         tmFeatureType.getName(),
411         finishedAtOffset,
412         processTime);
413     updateResponse = this.solrClient.commit();
414     logger.trace("Update response commit status: {}", updateResponse.getStatus());
415 
416     if (indexSkippedCounter > 0) {
417       logger.warn(
418           "{} features were skipped because no search or display values were found.", indexSkippedCounter);
419     }
420 
421     return searchIndexRepository.save(searchIndex
422         .setLastIndexed(finishedAtOffset)
423         .setStatus(SearchIndex.Status.INDEXED)
424         .setSummary(summary.total(total != null ? total : indexCounter)
425             .skippedCounter(indexSkippedCounter)
426             .duration(BigDecimal.valueOf(processTime.getSeconds())
427                 .add(BigDecimal.valueOf(processTime.getNano(), 9))
428                 .doubleValue())
429             .errorMessage(null)));
430   }
431 
432   /**
433    * Clear the index for a layer.
434    *
435    * @param searchLayerId the layer id
436    * @throws IOException if an I/O error occurs
437    * @throws SolrServerException if a Solr error occurs
438    */
439   public void clearIndexForLayer(@NotNull Long searchLayerId) throws IOException, SolrServerException {
440 
441     QueryResponse response =
442         solrClient.query(new SolrQuery("exists(query(" + SEARCH_LAYER + ":" + searchLayerId + "))"));
443     if (response.getResults().getNumFound() > 0) {
444       logger.info("Clearing index for searchLayer {}", searchLayerId);
445       UpdateResponse updateResponse = solrClient.deleteByQuery(SEARCH_LAYER + ":" + searchLayerId);
446       logger.trace("Delete response status: {}", updateResponse.getStatus());
447       updateResponse = solrClient.commit();
448       logger.trace("Commit response status: {}", updateResponse.getStatus());
449     } else {
450       logger.info("No index to clear for layer {}", searchLayerId);
451     }
452   }
453 
454   /**
455    * Search in the index for a layer. The given query is augmented to filter on the {@code solrLayerId}.
456    *
457    * @param searchIndex the search index
458    * @param solrQuery the query, when {@code null} or empty, the query is set to {@code *} (match all)
459    * @param solrPoint the point to search around, in (x y) format
460    * @param solrDistance the distance to search around the point in Solr distance units (kilometers)
461    * @param start the start index, starting at 0
462    * @param numResultsToReturn the number of results to return
463    * @return the documents
464    * @throws IOException if an I/O error occurs
465    * @throws SolrServerException if a Solr error occurs
466    */
467   public SearchResponse findInIndex(
468       @NotNull SearchIndex searchIndex,
469       String solrQuery,
470       String solrFilterQuery,
471       String solrPoint,
472       Double solrDistance,
473       int start,
474       int numResultsToReturn,
475       String applicationCrs)
476       throws IOException, SolrServerException, SolrException {
477 
478     if (null == solrQuery || solrQuery.isBlank()) {
479       solrQuery = "*";
480     }
481 
482     logger.info("Query index for '{}' in {} (id {})", solrQuery, searchIndex.getName(), searchIndex.getId());
483 
484     MathTransform toApplication = null;
485     MathTransform toSource = null;
486 
487     if (searchIndex.getSourceCrs() != null && applicationCrs != null) {
488       try {
489         toApplication = TransformationUtil.getTransformation(searchIndex.getSourceCrs(), applicationCrs);
490         toSource = TransformationUtil.getTransformation(applicationCrs, searchIndex.getSourceCrs());
491       } catch (FactoryException e) {
492         logger.error(
493             "Could not create transformations between search index CRS {} and application CRS {}",
494             searchIndex.getSourceCrs(),
495             applicationCrs,
496             e);
497       }
498     }
499 
500     final MathTransform resultTransform = toApplication;
501 
502     // TODO We could escape special/syntax characters, but that also prevents using
503     //      keys like ~ and *
504     // solrQuery = ClientUtils.escapeQueryChars(solrQuery);
505 
506     final SolrQuery query = new SolrQuery(INDEX_SEARCH_FIELD + ":" + solrQuery)
507         .setShowDebugInfo(logger.isDebugEnabled())
508         .setTimeAllowed(solrQueryTimeout)
509         .setIncludeScore(true)
510         .setFields(SEARCH_ID_FIELD, INDEX_DISPLAY_FIELD, INDEX_GEOM_FIELD)
511         .addFilterQuery(SEARCH_LAYER + ":" + searchIndex.getId())
512         .setSort("score", SolrQuery.ORDER.desc)
513         .addSort(SEARCH_ID_FIELD, SolrQuery.ORDER.asc)
514         .setRows(numResultsToReturn)
515         .setStart(start);
516 
517     if (null != solrFilterQuery && !solrFilterQuery.isBlank()) {
518       query.addFilterQuery(solrFilterQuery);
519     }
520     if (null != solrPoint && null != solrDistance) {
521       if (null == solrFilterQuery
522           || !(solrFilterQuery.startsWith("{!geofilt") || solrFilterQuery.startsWith("{!bbox"))) {
523         query.addFilterQuery("{!geofilt sfield=" + INDEX_GEOM_FIELD + "}");
524       }
525 
526       String transformedSolrPoint = solrPoint;
527 
528       if (toSource != null) {
529         Geometry pointGeometry = GeometryProcessor.wktToGeometry("POINT (" + solrPoint + ")");
530         if (pointGeometry != null) {
531           Geometry transformedPoint = GeometryProcessor.transformGeometry(pointGeometry, toSource);
532           transformedSolrPoint =
533               transformedPoint.getCoordinate().x + " " + transformedPoint.getCoordinate().y;
534         }
535       }
536 
537       query.add("pt", transformedSolrPoint);
538       query.add("d", solrDistance.toString());
539     }
540     query.set("q.op", "AND");
541     logger.debug("Solr query: {}", query);
542 
543     final QueryResponse response = solrClient.query(query);
544     logger.trace("response: {}", response);
545 
546     final SolrDocumentList solrDocumentList = response.getResults();
547     logger.debug("Found {} solr documents", solrDocumentList.getNumFound());
548     final SearchResponse searchResponse = new SearchResponse()
549         .total(solrDocumentList.getNumFound())
550         .start(response.getResults().getStart())
551         .maxScore(solrDocumentList.getMaxScore());
552     response.getResults().forEach(solrDocument -> {
553       List<String> displayValues = solrDocument.getFieldValues(INDEX_DISPLAY_FIELD).stream()
554           .map(Object::toString)
555           .toList();
556       Object geom = solrDocument.getFieldValue(INDEX_GEOM_FIELD);
557       if (geom != null) {
558         String geometry = geom.toString();
559 
560         if (resultTransform != null) {
561           Geometry parsedGeometry = GeometryProcessor.wktToGeometry(geometry);
562           if (parsedGeometry != null) {
563             geometry = GeometryProcessor.geometryToWKT(
564                 GeometryProcessor.transformGeometry(parsedGeometry, resultTransform));
565           }
566         }
567 
568         searchResponse.addDocumentsItem(new SearchDocument()
569             .fid(solrDocument.getFieldValue(SEARCH_ID_FIELD).toString())
570             .geometry(geometry)
571             .displayValues(displayValues));
572       }
573     });
574 
575     return searchResponse;
576   }
577 
578   /**
579    * Close the wrapped Solr client.
580    *
581    * @throws IOException if an I/O error occurs
582    */
583   @Override
584   public void close() throws IOException {
585     if (null != this.solrClient) this.solrClient.close();
586   }
587 
588   private boolean checkSchemaIfFieldExists(String fieldName) {
589     SchemaRequest.Field fieldCheck = new SchemaRequest.Field(fieldName);
590     try {
591       SchemaResponse.FieldResponse isField = fieldCheck.process(solrClient);
592       logger.debug("Field {} exists", isField.getField());
593       return true;
594     } catch (SolrServerException | RemoteSolrException e) {
595       logger.debug("Field {} does not exist or could not be retrieved. Assuming it does not exist.", fieldName);
596     } catch (IOException e) {
597       logger.error("Tried getting field: {}, but failed.", fieldName, e);
598     }
599     return false;
600   }
601 
602   /**
603    * @param fieldName the name of the field to create
604    * @throws SolrServerException if a Solr error occurs
605    * @throws IOException if an I/O error occurs
606    */
607   private void createSchemaFieldIfNotExists(String fieldName) throws SolrServerException, IOException {
608     if (!checkSchemaIfFieldExists(fieldName)) {
609       logger.info("Creating Solr field {}.", fieldName);
610       SchemaRequest.AddField schemaRequest = solrSearchFields.get(fieldName);
611       SolrResponse response = schemaRequest.process(solrClient);
612       logger.debug("Field type {} created", response);
613       solrClient.commit();
614     }
615   }
616 
617   /** Programmatically create the schema if it does not exist. */
618   private void createSchemaIfNotExists() {
619     solrSearchFields.forEach((key, value) -> {
620       try {
621         if (key.equals(INDEX_GEOM_FIELD)) {
622           createGeometryFieldTypeIfNotExists();
623         }
624         createSchemaFieldIfNotExists(key);
625       } catch (SolrServerException | IOException e) {
626         logger.error(
627             "Error creating schema field: {} indexing may fail. Details: {}",
628             key,
629             e.getLocalizedMessage(),
630             e);
631       }
632     });
633   }
634 
635   private void createGeometryFieldTypeIfNotExists() throws SolrServerException, IOException {
636     SchemaRequest.FieldType fieldTypeCheck = new SchemaRequest.FieldType(SOLR_SPATIAL_FIELDNAME);
637     try {
638       SchemaResponse.FieldTypeResponse isFieldType = fieldTypeCheck.process(solrClient);
639       logger.debug("Field type {} exists", isFieldType.getFieldType());
640       return;
641     } catch (SolrServerException | RemoteSolrException e) {
642       logger.debug(
643           "Field type {} does not exist or could not be retrieved. Assuming it does not exist.",
644           SOLR_SPATIAL_FIELDNAME);
645     } catch (IOException e) {
646       logger.error("Tried getting field type: {}, but failed.", SOLR_SPATIAL_FIELDNAME, e);
647     }
648 
649     logger.info(
650         "Creating Solr field type for {} with validation rule {}",
651         SOLR_SPATIAL_FIELDNAME,
652         solrGeometryValidationRule);
653     FieldTypeDefinition spatialFieldTypeDef = new FieldTypeDefinition();
654     Map<String, Object> spatialFieldAttributes = new HashMap<>(Map.of(
655         "name", SOLR_SPATIAL_FIELDNAME,
656         "class", "solr.SpatialRecursivePrefixTreeFieldType",
657         "spatialContextFactory", "JTS",
658         "geo", false,
659         "distanceUnits", "kilometers",
660         "distCalculator", "cartesian",
661         "format", "WKT",
662         "autoIndex", true,
663         "distErrPct", "0.025",
664         "maxDistErr", "0.001"));
665     spatialFieldAttributes.putAll(Map.of(
666         "prefixTree",
667         "packedQuad",
668         // see
669         // https://locationtech.github.io/spatial4j/apidocs/org/locationtech/spatial4j/context/jts/ValidationRule.html
670         "validationRule",
671         this.solrGeometryValidationRule,
672         // NOTE THE ODDITY in coordinate order of "worldBounds",
673         // "ENVELOPE(minX, maxX, maxY, minY)"
674         "worldBounds",
675         // webmercator / EPSG:3857 projected bounds
676         "ENVELOPE(-20037508.34, 20037508.34, 20048966.1, -20048966.1)"
677         // Amersfoort/RD new / EPSG:28992 projected bounds
678         // "ENVELOPE(482.06, 284182.97, 637049.52, 306602.42)"
679         ));
680     spatialFieldTypeDef.setAttributes(spatialFieldAttributes);
681     SchemaRequest.AddFieldType spatialFieldType = new SchemaRequest.AddFieldType(spatialFieldTypeDef);
682     spatialFieldType.process(solrClient);
683     solrClient.commit();
684   }
685 }