summaryrefslogtreecommitdiff
path: root/core/src/test/java/org/elasticsearch/index/query/GeoPolygonQueryBuilderTests.java
blob: 4a34ef5ffb00bf009302b2efee038cc6277c2fed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch 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.elasticsearch.index.query;

import com.spatial4j.core.shape.jts.JtsGeometry;
import com.vividsolutions.jts.geom.Coordinate;

import org.apache.lucene.search.GeoPointInPolygonQuery;
import org.apache.lucene.search.Query;
import org.elasticsearch.Version;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.geo.GeoUtils;
import org.elasticsearch.common.geo.builders.ShapeBuilder;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.search.geo.GeoPolygonQuery;
import org.elasticsearch.test.geo.RandomShapeGenerator;
import org.elasticsearch.test.geo.RandomShapeGenerator.ShapeType;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static org.elasticsearch.test.StreamsUtils.copyToStringFromClasspath;
import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;

public class GeoPolygonQueryBuilderTests extends AbstractQueryTestCase<GeoPolygonQueryBuilder> {
    @Override
    protected GeoPolygonQueryBuilder doCreateTestQueryBuilder() {
        List<GeoPoint> polygon = randomPolygon(randomIntBetween(4, 50));
        GeoPolygonQueryBuilder builder = new GeoPolygonQueryBuilder(GEO_POINT_FIELD_NAME, polygon);
        if (randomBoolean()) {
            builder.setValidationMethod(randomFrom(GeoValidationMethod.values()));
        }
        return builder;
    }

    @Override
    protected void doAssertLuceneQuery(GeoPolygonQueryBuilder queryBuilder, Query query, QueryShardContext context) throws IOException {
        Version version = context.indexVersionCreated();
        if (version.before(Version.V_2_2_0)) {
            assertLegacyQuery(queryBuilder, query);
        } else {
            assertGeoPointQuery(queryBuilder, query);
        }
    }

    private void assertLegacyQuery(GeoPolygonQueryBuilder queryBuilder, Query query) {
        assertThat(query, instanceOf(GeoPolygonQuery.class));
        GeoPolygonQuery geoQuery = (GeoPolygonQuery) query;
        assertThat(geoQuery.fieldName(), equalTo(queryBuilder.fieldName()));
        List<GeoPoint> queryBuilderPoints = queryBuilder.points();
        GeoPoint[] queryPoints = geoQuery.points();
        assertThat(queryPoints.length, equalTo(queryBuilderPoints.size()));
        if (GeoValidationMethod.isCoerce(queryBuilder.getValidationMethod())) {
            for (int i = 0; i < queryBuilderPoints.size(); i++) {
                GeoPoint queryBuilderPoint = queryBuilderPoints.get(i);
                GeoPoint pointCopy = new GeoPoint(queryBuilderPoint);
                GeoUtils.normalizePoint(pointCopy, true, true);
                assertThat(queryPoints[i], equalTo(pointCopy));
            }
        } else {
            for (int i = 0; i < queryBuilderPoints.size(); i++) {
                assertThat(queryPoints[i], equalTo(queryBuilderPoints.get(i)));
            }
        }
    }

    private void assertGeoPointQuery(GeoPolygonQueryBuilder queryBuilder, Query query) {
        assertThat(query, instanceOf(GeoPointInPolygonQuery.class));
        GeoPointInPolygonQuery geoQuery = (GeoPointInPolygonQuery) query;
        assertThat(geoQuery.getField(), equalTo(queryBuilder.fieldName()));
        List<GeoPoint> queryBuilderPoints = queryBuilder.points();
        double[] lats = geoQuery.getLats();
        double[] lons = geoQuery.getLons();
        assertThat(lats.length, equalTo(queryBuilderPoints.size()));
        assertThat(lons.length, equalTo(queryBuilderPoints.size()));
        for (int i=0; i < queryBuilderPoints.size(); ++i) {
            final GeoPoint queryBuilderPoint = queryBuilderPoints.get(i);
            final GeoPoint pointCopy = new GeoPoint(queryBuilderPoint);
            GeoUtils.normalizePoint(pointCopy);
            assertThat(lats[i], closeTo(pointCopy.getLat(), 1E-5D));
            assertThat(lons[i], closeTo(pointCopy.getLon(), 1E-5D));
        }
    }

    /**
     * Overridden here to ensure the test is only run if at least one type is
     * present in the mappings. Geo queries do not execute if the field is not
     * explicitly mapped
     */
    @Override
    public void testToQuery() throws IOException {
        assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0);
        super.testToQuery();
    }

    public List<GeoPoint> randomPolygon(int numPoints) {
        ShapeBuilder shapeBuilder = null;
        // This is a temporary fix because sometimes the RandomShapeGenerator
        // returns null. This is if there is an error generating the polygon. So
        // in this case keep trying until we successfully generate one
        while (shapeBuilder == null) {
            shapeBuilder = RandomShapeGenerator.createShapeWithin(getRandom(), null, ShapeType.POLYGON);
        }
        JtsGeometry shape = (JtsGeometry) shapeBuilder.build();
        Coordinate[] coordinates = shape.getGeom().getCoordinates();
        ArrayList<GeoPoint> polygonPoints = new ArrayList<>();
        for (Coordinate coord : coordinates) {
            polygonPoints.add(new GeoPoint(coord.y, coord.x));
        }
        return polygonPoints;
    }

    public void testNullFieldName() {
        try {
            new GeoPolygonQueryBuilder(null, randomPolygon(5));
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            assertThat(e.getMessage(), is("fieldName must not be null"));
        }
    }

    public void testEmptyPolygon() {
        try {
            if (randomBoolean()) {
                new GeoPolygonQueryBuilder(GEO_POINT_FIELD_NAME, new ArrayList<GeoPoint>());
            } else {
                new GeoPolygonQueryBuilder(GEO_POINT_FIELD_NAME, null);
            }
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            assertThat(e.getMessage(), is("polygon must not be null or empty"));
        }
    }

    public void testInvalidClosedPolygon() {
        List<GeoPoint> points = new ArrayList<>();
        points.add(new GeoPoint(0, 90));
        points.add(new GeoPoint(90, 90));
        points.add(new GeoPoint(0, 90));
        try {
            new GeoPolygonQueryBuilder(GEO_POINT_FIELD_NAME, points);
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            assertThat(e.getMessage(), is("too few points defined for geo_polygon query"));
        }
    }

    public void testInvalidOpenPolygon() {
        List<GeoPoint> points = new ArrayList<>();
        points.add(new GeoPoint(0, 90));
        points.add(new GeoPoint(90, 90));
        try {
            new GeoPolygonQueryBuilder(GEO_POINT_FIELD_NAME, points);
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            assertThat(e.getMessage(), is("too few points defined for geo_polygon query"));
        }
    }

    public void testDeprecatedXContent() throws IOException {
        XContentBuilder builder = XContentFactory.jsonBuilder().prettyPrint();
        builder.startObject();
        builder.startObject("geo_polygon");
        builder.startObject(GEO_POINT_FIELD_NAME);
        builder.startArray("points");
        builder.value("0,0");
        builder.value("0,90");
        builder.value("90,90");
        builder.value("90,0");
        builder.endArray();
        builder.endObject();
        builder.field("normalize", true); // deprecated
        builder.endObject();
        builder.endObject();
        try {
            parseQuery(builder.string());
            fail("normalize is deprecated");
        } catch (IllegalArgumentException ex) {
            assertEquals("Deprecated field [normalize] used, expected [coerce] instead", ex.getMessage());
        }
    }

    public void testParsingAndToQueryParsingExceptions() throws IOException {
        String[] brokenFiles = new String[]{
                "/org/elasticsearch/index/query/geo_polygon_exception_1.json",
                "/org/elasticsearch/index/query/geo_polygon_exception_2.json",
                "/org/elasticsearch/index/query/geo_polygon_exception_3.json",
                "/org/elasticsearch/index/query/geo_polygon_exception_4.json",
                "/org/elasticsearch/index/query/geo_polygon_exception_5.json"
        };
        for (String brokenFile : brokenFiles) {
            String query = copyToStringFromClasspath(brokenFile);
            try {
                parseQuery(query);
                fail("parsing a broken geo_polygon filter didn't fail as expected while parsing: " + brokenFile);
            } catch (ParsingException e) {
                // success!
            }
        }
    }

    public void testParsingAndToQuery1() throws IOException {
        assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0);
        String query = "{\n" +
                "    \"geo_polygon\":{\n" +
                "        \"" + GEO_POINT_FIELD_NAME + "\":{\n" +
                "            \"points\":[\n" +
                "                [-70, 40],\n" +
                "                [-80, 30],\n" +
                "                [-90, 20]\n" +
                "            ]\n" +
                "        }\n" +
                "    }\n" +
                "}\n";
        assertGeoPolygonQuery(query);
    }

    public void testParsingAndToQuery2() throws IOException {
        assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0);
        String query = "{\n" +
                "    \"geo_polygon\":{\n" +
                "        \"" + GEO_POINT_FIELD_NAME + "\":{\n" +
                "            \"points\":[\n" +
                "                {\n" +
                "                    \"lat\":40,\n" +
                "                    \"lon\":-70\n" +
                "                },\n" +
                "                {\n" +
                "                    \"lat\":30,\n" +
                "                    \"lon\":-80\n" +
                "                },\n" +
                "                {\n" +
                "                    \"lat\":20,\n" +
                "                    \"lon\":-90\n" +
                "                }\n" +
                "            ]\n" +
                "        }\n" +
                "    }\n" +
                "}\n";
        assertGeoPolygonQuery(query);
    }

    public void testParsingAndToQuery3() throws IOException {
        assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0);
        String query = "{\n" +
                "    \"geo_polygon\":{\n" +
                "        \"" + GEO_POINT_FIELD_NAME + "\":{\n" +
                "            \"points\":[\n" +
                "                \"40, -70\",\n" +
                "                \"30, -80\",\n" +
                "                \"20, -90\"\n" +
                "            ]\n" +
                "        }\n" +
                "    }\n" +
                "}\n";
        assertGeoPolygonQuery(query);
    }

    public void testParsingAndToQuery4() throws IOException {
        assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0);
        String query = "{\n" +
                "    \"geo_polygon\":{\n" +
                "        \"" + GEO_POINT_FIELD_NAME + "\":{\n" +
                "            \"points\":[\n" +
                "                \"drn5x1g8cu2y\",\n" +
                "                \"30, -80\",\n" +
                "                \"20, -90\"\n" +
                "            ]\n" +
                "        }\n" +
                "    }\n" +
                "}\n";
        assertGeoPolygonQuery(query);
    }

    private void assertGeoPolygonQuery(String query) throws IOException {
        QueryShardContext context = createShardContext();
        Version version = context.indexVersionCreated();
        Query parsedQuery = parseQuery(query).toQuery(context);
        if (version.before(Version.V_2_2_0)) {
            GeoPolygonQuery filter = (GeoPolygonQuery) parsedQuery;
            assertThat(filter.fieldName(), equalTo(GEO_POINT_FIELD_NAME));
            assertThat(filter.points().length, equalTo(4));
            assertThat(filter.points()[0].lat(), closeTo(40, 0.00001));
            assertThat(filter.points()[0].lon(), closeTo(-70, 0.00001));
            assertThat(filter.points()[1].lat(), closeTo(30, 0.00001));
            assertThat(filter.points()[1].lon(), closeTo(-80, 0.00001));
            assertThat(filter.points()[2].lat(), closeTo(20, 0.00001));
            assertThat(filter.points()[2].lon(), closeTo(-90, 0.00001));
        } else {
            GeoPointInPolygonQuery q = (GeoPointInPolygonQuery) parsedQuery;
            assertThat(q.getField(), equalTo(GEO_POINT_FIELD_NAME));
            final double[] lats = q.getLats();
            final double[] lons = q.getLons();
            assertThat(lats.length, equalTo(4));
            assertThat(lons.length, equalTo(4));
            assertThat(lats[0], closeTo(40, 1E-5));
            assertThat(lons[0], closeTo(-70, 1E-5));
            assertThat(lats[1], closeTo(30, 1E-5));
            assertThat(lons[1], closeTo(-80, 1E-5));
            assertThat(lats[2], closeTo(20, 1E-5));
            assertThat(lons[2], closeTo(-90, 1E-5));
            assertThat(lats[3], equalTo(lats[0]));
            assertThat(lons[3], equalTo(lons[0]));
        }
    }

    public void testFromJson() throws IOException {
        String json =
                "{\n" + 
                "  \"geo_polygon\" : {\n" + 
                "    \"person.location\" : {\n" + 
                "      \"points\" : [ [ -70.0, 40.0 ], [ -80.0, 30.0 ], [ -90.0, 20.0 ], [ -70.0, 40.0 ] ]\n" + 
                "    },\n" + 
                "    \"coerce\" : false,\n" + 
                "    \"ignore_malformed\" : false,\n" + 
                "    \"boost\" : 1.0\n" + 
                "  }\n" + 
                "}";
        GeoPolygonQueryBuilder parsed = (GeoPolygonQueryBuilder) parseQuery(json);
        checkGeneratedJson(json, parsed);
        assertEquals(json, 4, parsed.points().size());
    }
}