SOLR-13467: Include the S2 Geometry lib to make it simpler to use prefixTree="s2" on a Geo3D spatial field.

* Improved documentation on Geo3D.
* Better testing for Geo3D.
This commit is contained in:
David Smiley 2019-05-15 22:15:13 -04:00
parent bd64ed6d2a
commit 3a88ab616c
8 changed files with 291 additions and 38 deletions

View File

@ -36,7 +36,7 @@ Upgrade Notes
* SOLR-12055 introduces async logging by default. There's a small window where log messages may be lost
in the event of some hard crash. Switch back to synchronous logging if this is unacceptable, see
see commeints in the log4j2 configuration files (log4j2.xml by default).
see comments in the log4j2 configuration files (log4j2.xml by default).
* SOLR-12891: MacroExpander will no longer will expand URL parameters inside of the 'expr' parameter (used by streaming
expressions) Additionally, users are advised to use the 'InjectionDefense' class when constructing streaming
@ -89,6 +89,7 @@ New Features
information about the replicas of a collection (Erick Erickson)
* SOLR-13468: autoscaling/suggestions should be able to give suggestions from config sent as a payload (noble)
Other Changes
----------------------
@ -96,6 +97,9 @@ Other Changes
* SOLR-13437: noggit json parser is forked into solrj (noble)
* SOLR-13467: Include the S2 Geometry lib to make it simpler to use prefixTree="s2" on a Geo3D spatial field.
Improved documentation on Geo3D too. (David Smiley)
================== 8.1.0 ==================
Consult the LUCENE_CHANGES.txt file for additional, low level, changes in this release.

View File

@ -45,6 +45,7 @@
<dependency org="org.restlet.jee" name="org.restlet" rev="${/org.restlet.jee/org.restlet}" conf="compile"/>
<dependency org="org.restlet.jee" name="org.restlet.ext.servlet" rev="${/org.restlet.jee/org.restlet.ext.servlet}" conf="compile"/>
<dependency org="com.carrotsearch" name="hppc" rev="${/com.carrotsearch/hppc}" conf="compile"/>
<dependency org="io.sgr" name="s2-geometry-library-java" rev="${/io.sgr/s2-geometry-library-java}" conf="compile"/>
<dependency org="org.apache.logging.log4j" name="log4j-api" rev="${/org.apache.logging.log4j/log4j-api}" conf="compile"/>
<dependency org="org.apache.logging.log4j" name="log4j-core" rev="${/org.apache.logging.log4j/log4j-core}" conf="compile"/>

View File

@ -57,7 +57,10 @@
<fieldType name="srptgeom" class="solr.RptWithGeometrySpatialField"/>
<fieldType name="srptgeom_geo3d" class="solr.RptWithGeometrySpatialField"
spatialContextFactory="Geo3D" planetModel="wgs84"/><!-- or sphere -->
spatialContextFactory="Geo3D" prefixTree="geohash" planetModel="wgs84"/><!-- or sphere -->
<fieldType name="srptgeom_s2_geo3d" class="solr.RptWithGeometrySpatialField"
spatialContextFactory="Geo3D" prefixTree="s2" planetModel="sphere"/>
<fieldType name="bbox" class="solr.BBoxField"
numberType="tdoubleDV" distanceUnits="degrees" storeSubFields="false"/>
@ -79,6 +82,7 @@
<field name="pointvector" type="pointvector"/>
<field name="srptgeom" type="srptgeom"/>
<field name="srptgeom_geo3d" type="srptgeom_geo3d"/>
<field name="srptgeom_s2_geo3d" type="srptgeom_s2_geo3d"/>
<field name="bbox" type="bbox"/>
<field name="pbbox" type="pbbox"/>
<field name="bbox_ndv" type="bbox_ndv"/>

View File

@ -123,19 +123,27 @@ public class TestSolr4Spatial2 extends SolrTestCaseJ4 {
@Test
public void testRptWithGeometryField() throws Exception {
testRptWithGeometryField("srptgeom");//note: fails with "srpt_geohash" because it's not as precise
//note: fails with "srpt_geohash" because it's not as precise
final boolean testCache = true;
final boolean testHeatmap = true;
final boolean testPolygon = false; // default spatialContext doesn't handle this
testRptWithGeometryField("srptgeom", testCache, testHeatmap, testPolygon);
}
@Test
public void testRptWithGeometryGeo3dField() throws Exception {
String fieldName = "srptgeom_geo3d";
testRptWithGeometryField(fieldName);
final boolean testCache = true;
final boolean testHeatmap = true;
final boolean testPolygon = true;
testRptWithGeometryField("srptgeom_geo3d", testCache, testHeatmap, testPolygon);
}
// show off that Geo3D supports polygons
String polygonWKT = "POLYGON((-11 12, 10.5 12, -11 11, -11 12))"; //right-angle triangle
assertJQ(req(
"q", "{!cache=false field f=" + fieldName + "}Intersects(" + polygonWKT + ")",
"sort", "id asc"), "/response/numFound==2");
@Test
public void testRptWithGeometryGeo3dS2Field() throws Exception {
final boolean testCache = false; // the test data is designed to provoke the cache for non-S2
final boolean testHeatmap = false; // incompatible
final boolean testPolygon = true;
testRptWithGeometryField("srptgeom_s2_geo3d", testCache, testHeatmap, testPolygon);
}
@Test @Repeat(iterations = 10)
@ -263,7 +271,7 @@ public class TestSolr4Spatial2 extends SolrTestCaseJ4 {
}
}
private void testRptWithGeometryField(String fieldName) throws Exception {
private void testRptWithGeometryField(String fieldName, boolean testCache, boolean testHeatmap, boolean testPolygon) throws Exception {
assertU(adoc("id", "0", fieldName, "ENVELOPE(-10, 20, 15, 10)"));
assertU(adoc("id", "1", fieldName, "BUFFER(POINT(-10 15), 5)"));//circle at top-left corner
assertU(optimize("maxSegments", "1"));// one segment.
@ -276,39 +284,60 @@ public class TestSolr4Spatial2 extends SolrTestCaseJ4 {
"sort", "id asc");
assertJQ(sameReq, "/response/numFound==1", "/response/docs/[0]/id=='1'");
// The tricky thing is verifying the cache works correctly...
if (testCache) {
// The tricky thing is verifying the cache works correctly...
MetricsMap cacheMetrics = (MetricsMap) ((SolrMetricManager.GaugeWrapper)h.getCore().getCoreMetricManager().getRegistry().getMetrics().get("CACHE.searcher.perSegSpatialFieldCache_" + fieldName)).getGauge();
assertEquals("1", cacheMetrics.getValue().get("cumulative_inserts").toString());
assertEquals("0", cacheMetrics.getValue().get("cumulative_hits").toString());
MetricsMap cacheMetrics = (MetricsMap) ((SolrMetricManager.GaugeWrapper)h.getCore().getCoreMetricManager().getRegistry().getMetrics().get("CACHE.searcher.perSegSpatialFieldCache_" + fieldName)).getGauge();
assertEquals("1", cacheMetrics.getValue().get("cumulative_inserts").toString());
assertEquals("0", cacheMetrics.getValue().get("cumulative_hits").toString());
// Repeat the query earlier
assertJQ(sameReq, "/response/numFound==1", "/response/docs/[0]/id=='1'");
assertEquals("1", cacheMetrics.getValue().get("cumulative_hits").toString());
// Repeat the query earlier
assertJQ(sameReq, "/response/numFound==1", "/response/docs/[0]/id=='1'");
assertEquals("1", cacheMetrics.getValue().get("cumulative_hits").toString());
assertEquals("1 segment",
1, getSearcher().getRawReader().leaves().size());
// Get key of first leaf reader -- this one contains the match for sure.
Object leafKey1 = getFirstLeafReaderKey();
assertEquals("1 segment",
1, getSearcher().getRawReader().leaves().size());
// Get key of first leaf reader -- this one contains the match for sure.
Object leafKey1 = getFirstLeafReaderKey();
// add new segment
assertU(adoc("id", "3"));
// add new segment
assertU(adoc("id", "3"));
assertU(commit()); // sometimes merges (to one seg), sometimes won't
assertU(commit()); // sometimes merges (to one seg), sometimes won't
// can still find the same document
assertJQ(sameReq, "/response/numFound==1", "/response/docs/[0]/id=='1'");
// can still find the same document
assertJQ(sameReq, "/response/numFound==1", "/response/docs/[0]/id=='1'");
// When there are new segments, we accumulate another hit. This tests the cache was not blown away on commit.
// Checking equality for the first reader's cache key indicates whether the cache should still be valid.
Object leafKey2 = getFirstLeafReaderKey();
assertEquals(leafKey1.equals(leafKey2) ? "2" : "1", cacheMetrics.getValue().get("cumulative_hits").toString());
// When there are new segments, we accumulate another hit. This tests the cache was not blown away on commit.
// Checking equality for the first reader's cache key indicates whether the cache should still be valid.
Object leafKey2 = getFirstLeafReaderKey();
assertEquals(leafKey1.equals(leafKey2) ? "2" : "1", cacheMetrics.getValue().get("cumulative_hits").toString());
}
if (testHeatmap) {
// Now try to see if heatmaps work:
assertJQ(req("q", "*:*", "facet", "true", FacetParams.FACET_HEATMAP, fieldName, "json.nl", "map"),
"/facet_counts/facet_heatmaps/" + fieldName + "/minX==-180.0");
}
// Now try to see if heatmaps work:
assertJQ(req("q", "*:*", "facet", "true", FacetParams.FACET_HEATMAP, fieldName, "json.nl", "map"),
"/facet_counts/facet_heatmaps/" + fieldName + "/minX==-180.0");
if (testPolygon) {
String polygonWKT = "POLYGON((-11 12, -11 11, 10.5 12, -11 12))"; //right-angle triangle. Counter-clockwise order
assertJQ(req(
"q", "{!cache=false field f=" + fieldName + "}Intersects(" + polygonWKT + ")",
"sort", "id asc"), "/response/numFound==2");
assertU(adoc("id", "9",
fieldName, "POLYGON((" + // rectangle. Counter-clockwise order.
"-118.080201721669 54.5864541583249," +
"-118.080078279314 54.5864541583249," +
"-118.080078279314 54.5865258517606," +
"-118.080201721669 54.5865258517606," +
"-118.080201721669 54.5864541583249))" ));
assertU(commit());
// should NOT match
assertJQ(req("q", fieldName+":[55.0260828,-115.5085624 TO 55.02646,-115.507337]"),
"/response/numFound==0");
}
}
protected SolrIndexSearcher getSearcher() {

View File

@ -0,0 +1 @@
f95b25589b40b5b0965deb592445073ff3efa299

View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed 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.

View File

@ -249,7 +249,9 @@ The name of the field type.
This should be `solr.SpatialRecursivePrefixTreeFieldType`. But be aware that the Lucene spatial module includes some other so-called "spatial strategies" other than RPT, notably TermQueryPT*, BBox, PointVector*, and SerializedDV. Solr requires a field type to parallel these in order to use them. The asterisked ones have them.
`spatialContextFactory`::
This is a Java class name to an internal extension point governing support for shape definitions & parsing. If you require polygon support, set this to `JTS` an alias for `org.locationtech.spatial4j.context.jts.JtsSpatialContextFactory`; otherwise it can be omitted. See important info below about JTS. (note: prior to Solr 6, the "org.locationtech.spatial4j" part was "com.spatial4j.core" and there used to be no convenience JTS alias)
This is a Java class name to an internal extension point governing support for shape definitions & parsing.
There are two built-in aliases for known implementations: `Geo3D` and `JTS`.
The default blank value does not support polygons.
`geo`::
If `true`, the default, latitude and longitude coordinates will be used and the mathematical model will generally be a sphere. If `false`, the coordinates will be generic X & Y on a 2D plane using Euclidean/Cartesian geometry.
@ -338,7 +340,7 @@ Beyond this Reference Guide and Spatila4j's docs, there are some details that re
Geo3D is the colloquial name of the Lucene spatial-3d module, included with Solr.
It's a computational geometry library implementing a variety of shapes (including polygons) on a sphere or WGS84 ellipsoid.
Geo3D is particularly suited for spatial applications where the geometries cover large distances across the globe.
Geo3D is particularly suited for spatial applications where the geometries cover large distances across the globe or are near the poles.
Geo3D is named as-such due to its internal implementation that uses geocentric coordinates (X,Y,Z),
*not* for 3-dimensional geometry, which it does not support.
Despite these internal details, you still supply latitude and longitude as you would normally in Solr.
@ -347,12 +349,22 @@ Set the `spatialContextFactory` attribute on the field type to `Geo3D`.
[source,xml]
----
<fieldType name="geom" class="solr.SpatialRecursivePrefixTreeFieldType"
spatialContextFactory="Geo3D" planetModel="WGS84"/><!-- or "sphere" -->
<fieldType name="geom"
class="solr.SpatialRecursivePrefixTreeFieldType"
spatialContextFactory="Geo3D"
prefixTree="s2"
planetModel="WGS84"/><!-- or "sphere" -->
----
Once the field type has been defined, define a field that uses it.
The `prefixTree="s2"` setting is optional and only possible with Geo3D.
It was developed with Geo3D in mind to be more efficient than the other grids.
IMPORTANT: When using Geo3D, the order of polygon points matters!
You must follow the so-called "right hand rule": the exterior ring must be counter-clockwise order and the interior holes must be clockwise.
If the order is wrong then the interpretation is inverted, thus the polygon will be interpreted as encompassing most of the globe.
=== RptWithGeometrySpatialField
The `RptWithGeometrySpatialField` field type is a derivative of `SpatialRecursivePrefixTreeFieldType` that also stores the original geometry internally in Lucene DocValues, which it uses to achieve accurate search. It can also be used for indexed point fields. The Intersects predicate (the default) is particularly fast, since many search results can be returned as an accurate hit without requiring a geometry check. This field type is configured just like RPT except that the default `distErrPct` is 0.15 (higher than 0.025) because the grid squares are purely for performance and not to fundamentally represent the shape.