Beispiel #1
0
        public static IndexQuery FromQueryString(string queryString)
        {
            var fields = queryString.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
                         .Select(segment =>
            {
                var parts = segment.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                if (parts.Length == 1)
                {
                    return(new { Key = parts[0], Value = string.Empty });
                }
                else
                {
                    return
                    (new
                    {
                        Key = parts[0],
                        Value = Uri.UnescapeDataString(parts[1])
                    });
                }
            }).ToLookup(f => f.Key, f => f.Value);

            var query = new IndexQuery
            {
                Query                = Uri.UnescapeDataString(fields["query"].FirstOrDefault() ?? ""),
                Start                = fields.GetStart(),
                Cutoff               = fields.GetCutOff(),
                CutoffEtag           = fields.GetCutOffEtag(),
                PageSize             = fields.GetPageSize(250),
                SkipTransformResults = fields.GetSkipTransformResults(),
                FieldsToFetch        = fields["fetch"].ToArray(),
                GroupBy              = fields["groupBy"].ToArray(),
                AggregationOperation = fields.GetAggregationOperation(),
                SortedFields         = fields["sort"]
                                       .EmptyIfNull()
                                       .Select(x => new SortedField(x))
                                       .ToArray()
            };

            double       lat = fields.GetLat(), lng = fields.GetLng(), radius = fields.GetRadius();
            SpatialUnits?units = fields.GetRadiusUnits();

            if (lat != 0 || lng != 0 || radius != 0)
            {
                return(new SpatialIndexQuery(query)
                {
                    QueryShape = SpatialIndexQuery.GetQueryShapeFromLatLon(lat, lng, radius),
                    RadiusUnitOverride = units,
                    SpatialRelation = SpatialRelation.Within,             /* TODO */
                    SpatialFieldName = Constants.DefaultSpatialFieldName, /* TODO */
                });
            }
            return(query);
        }
Beispiel #2
0
        public void Test()
        {
            using (IDocumentStore store = NewDocumentStore())
            {
                using (IDocumentSession session = store.OpenSession())
                {
                    session.Store(new MySpatialDocument
                    {
                        Id        = "spatials/1",
                        Latitude  = 48.3708044,
                        Longitude = 2.8028712999999925
                    });
                    session.SaveChanges();
                }

                new MySpatialIndex().Execute(store);

                WaitForIndexing(store);

                // Distance between the 2 tested points is 35.75km
                // (can be checked here: http://www.movable-type.co.uk/scripts/latlong.html

                using (IDocumentSession session = store.OpenSession())
                {
                    var result = session.Advanced.DocumentQuery <MySpatialDocument, MySpatialIndex>()
                                 // 1.025 is for the 2.5% uncertainty at the circle circumference
                                 .WithinRadiusOf(radius: 35.75 * 1.025, latitude: 48.6003516, longitude: 2.4632387000000335)
                                 .SingleOrDefault();

                    Assert.NotNull(result); // A location should be returned.

                    result = session.Advanced.DocumentQuery <MySpatialDocument, MySpatialIndex>()
                             .WithinRadiusOf(radius: 30, latitude: 48.6003516, longitude: 2.4632387000000335)
                             .SingleOrDefault();

                    Assert.Null(result); // No result should be returned.

                    result = session.Advanced.DocumentQuery <MySpatialDocument, MySpatialIndex>()
                             .WithinRadiusOf(radius: 33, latitude: 48.6003516, longitude: 2.4632387000000335)
                             .SingleOrDefault();

                    Assert.Null(result); // No result should be returned.

                    var shape = SpatialIndexQuery.GetQueryShapeFromLatLon(48.6003516, 2.4632387000000335, 33);
                    result = session.Advanced.DocumentQuery <MySpatialDocument, MySpatialIndex>()
                             .RelatesToShape(Constants.DefaultSpatialFieldName, shape, SpatialRelation.Intersects, 0)
                             .SingleOrDefault();

                    Assert.Null(result); // No result should be returned.
                }
            }
        }
Beispiel #3
0
        public IndexQuery CreateTemplateQuery()
        {
            var q = new IndexQuery
            {
                Query           = Query,
                DefaultOperator = DefaultOperator
            };

            if (SortBy != null && SortBy.Count > 0)
            {
                var sortedFields = new List <SortedField>();
                foreach (var sortByRef in SortBy)
                {
                    var sortBy = sortByRef.Value;
                    if (sortBy.EndsWith(QueryModel.SortByDescSuffix))
                    {
                        var field = sortBy.Remove(sortBy.Length - QueryModel.SortByDescSuffix.Length);
                        sortedFields.Add(new SortedField(field)
                        {
                            Descending = true
                        });
                    }
                    else
                    {
                        sortedFields.Add(new SortedField(sortBy));
                    }
                }
                q.SortedFields = sortedFields.ToArray();
            }

            if (ShowFields)
            {
                q.FieldsToFetch = new[] { Constants.AllFields }
            }
            ;

            q.DebugOptionGetIndexEntries = ShowEntries;

            q.SkipTransformResults = SkipTransformResults;
            if (IsSpatialQuerySupported && Latitude.HasValue && Longitude.HasValue)
            {
                q = new SpatialIndexQuery(q)
                {
                    QueryShape       = SpatialIndexQuery.GetQueryShapeFromLatLon(Latitude.Value, Longitude.Value, Radius.HasValue ? Radius.Value : 1),
                    SpatialRelation  = SpatialRelation.Within,
                    SpatialFieldName = Constants.DefaultSpatialFieldName,
                    DefaultOperator  = DefaultOperator
                };
            }

            return(q);
        }
Beispiel #4
0
        public void CanFilterByLocationAndSortByDistanceFromDifferentPointWDocQuery()
        {
            var queryResult = store.DatabaseCommands.Query("eventsByLatLng", new SpatialIndexQuery()
            {
                QueryShape       = SpatialIndexQuery.GetQueryShapeFromLatLon(filteredLat, filteredLng, filteredRadius),
                SpatialRelation  = SpatialRelation.Within,
                SpatialFieldName = Constants.DefaultSpatialFieldName,
                SortedFields     = new[]
                {
                    new SortedField(string.Format("{0};{1};{2}", Constants.DistanceFieldName, sortedLat, sortedLng))
                }
            });

            AssertResultsOrder(queryResult.Results.Select(x => x.Value <RavenJObject>("@metadata").Value <string>("@id")).ToArray());
        }
Beispiel #5
0
        public void does_culture_invariant_parameter_parsing_for_spatial_queries(CultureInfo cultureInfo)
        {
            using (new TemporaryCulture(cultureInfo))
            {
                var indexQuery = new SpatialIndexQuery
                {
                    DistanceErrorPercentage = 0.25,
                    QueryShape =
                        SpatialIndexQuery.GetQueryShapeFromLatLon(12.461334, 130.841904, 4.9)
                };
                var result = (SpatialIndexQuery)EncodeAndDecodeIndexQuery(indexQuery);

                Assert.Equal(indexQuery.DistanceErrorPercentage, result.DistanceErrorPercentage);
                Assert.Equal(indexQuery.QueryShape, result.QueryShape);
            }
        }
Beispiel #6
0
            public void ShouldMatchMakeFacetsOnLocation()
            {
                FacetResults facetvalues;

                using (var s = Store.OpenSession())
                {
                    var index = typeof(ByVehicle).Name;

                    facetvalues = Store.DatabaseCommands.GetFacets(
                        index: index,
                        query: new SpatialIndexQuery()
                    {
                        QueryShape       = SpatialIndexQuery.GetQueryShapeFromLatLon(new Darwin().Latitude, new Darwin().Longitude, 5),
                        SpatialRelation  = SpatialRelation.Within,
                        SpatialFieldName = Constants.DefaultSpatialFieldName,
                    },
                        facetSetupDoc: "facets/Vehicle");
                }

                Assert.NotNull(facetvalues);
                Assert.Equal(2, facetvalues.Results["Make"].Values.Count());
            }
Beispiel #7
0
        public void CanPerformSpatialSearchWithNulls()
        {
            var indexDefinition = new IndexDefinition
            {
                Map     = "from e in docs.Events select new { Tag = \"Event\", _ = SpatialGenerate(e.Latitude, e.Longitude) }",
                Indexes =
                {
                    { "Tag", FieldIndexing.NotAnalyzed }
                }
            };

            db.PutIndex("eventsByLatLng", indexDefinition);

            db.Put("Events/1", null,
                   RavenJObject.Parse(@"{""Venue"": ""Jimmy's Old Town Tavern"", ""Latitude"": null, ""Longitude"": null }"),
                   RavenJObject.Parse("{'Raven-Entity-Name': 'Events'}"), null);

            const double radius = 6.0;
            QueryResult  queryResult;

            do
            {
                queryResult = db.Query("eventsByLatLng", new SpatialIndexQuery()
                {
                    Query            = "Tag:[[Event]]",
                    QueryShape       = SpatialIndexQuery.GetQueryShapeFromLatLon(0, 0, radius),
                    SpatialRelation  = SpatialRelation.Within,
                    SpatialFieldName = Constants.DefaultSpatialFieldName,
                    SortedFields     = new[] { new SortedField("__distance"), }
                });
                if (queryResult.IsStale)
                {
                    Thread.Sleep(100);
                }
            } while (queryResult.IsStale);

            Assert.Equal(1, queryResult.Results.Count);
        }
 protected override object GenerateQueryWithinRadiusOf(string fieldName, double radius, double latitude, double longitude, double distanceErrorPct = 0.025, SpatialUnits radiusUnits = SpatialUnits.Kilometers)
 {
     return(GenerateSpatialQueryData(fieldName, SpatialIndexQuery.GetQueryShapeFromLatLon(latitude, longitude, radius, radiusUnits), SpatialRelation.Within, distanceErrorPct));
 }
Beispiel #9
0
        public void CanPerformSpatialSearch()
        {
            var indexDefinition = new IndexDefinition
            {
                Map     = "from e in docs.Events select new { Tag = \"Event\", _ = SpatialGenerate(e.Latitude, e.Longitude) }",
                Indexes =
                {
                    { "Tag", FieldIndexing.NotAnalyzed }
                }
            };

            db.PutIndex("eventsByLatLng", indexDefinition);

            var events = SpatialIndexTestHelper.GetEvents();

            for (int i = 0; i < events.Length; i++)
            {
                db.Put("Events/" + (i + 1), null,
                       RavenJObject.FromObject(events[i]),
                       RavenJObject.Parse("{'Raven-Entity-Name': 'Events'}"), null);
            }

            const double lat = 38.96939, lng = -77.386398;
            const double radiusInKm = 6.0 * 1.609344;
            QueryResult  queryResult;

            do
            {
                queryResult = db.Query("eventsByLatLng", new SpatialIndexQuery()
                {
                    Query            = "Tag:[[Event]]",
                    QueryShape       = SpatialIndexQuery.GetQueryShapeFromLatLon(lat, lng, radiusInKm),
                    SpatialRelation  = SpatialRelation.Within,
                    SpatialFieldName = Constants.DefaultSpatialFieldName,
                    SortedFields     = new[] { new SortedField("__distance"), }
                });
                if (queryResult.IsStale)
                {
                    Thread.Sleep(100);
                }
            } while (queryResult.IsStale);

            var expected = events.Count(e => GetGeographicalDistance(lat, lng, e.Latitude, e.Longitude) <= radiusInKm);

            Assert.Equal(expected, queryResult.Results.Count);
            Assert.Equal(7, queryResult.Results.Count);

            double previous = 0;

            foreach (var r in queryResult.Results)
            {
                Event e = r.JsonDeserialization <Event>();

                double distance = GetGeographicalDistance(lat, lng, e.Latitude, e.Longitude);
                Console.WriteLine("Venue: " + e.Venue + ", Distance " + distance);

                Assert.True(distance < radiusInKm);
                Assert.True(distance >= previous);
                previous = distance;
            }
        }
Beispiel #10
0
        public void CanSortByAnotherPropAnddistance()
        {
            var indexDefinition = new IndexDefinition
            {
                Map     = "from e in docs.Events select new { e.Venue, _ = SpatialGenerate(e.Latitude, e.Longitude) }",
                Indexes =
                {
                    { "Tag", FieldIndexing.NotAnalyzed }
                }
            };

            db.PutIndex("eventsByLatLng", indexDefinition);

            var events = new[]
            {
                new Event("b", 38.9579000, -77.3572000),
                new Event("b", 38.9690000, -77.3862000),
                new Event("b", 38.9510000, -77.4107000),

                new Event("a", 38.9579000, -77.3572000),
                new Event("a", 38.9690000, -77.3862000),
                new Event("a", 38.9510000, -77.4107000),
            };

            for (int i = 0; i < events.Length; i++)
            {
                db.Put("Events/" + (i + 1), null,
                       RavenJObject.FromObject(events[i]),
                       RavenJObject.Parse("{'Raven-Entity-Name': 'Events'}"), null);
            }

            const double lat = 38.96939, lng = -77.386398;
            const double radius = 6.0;
            QueryResult  queryResult;

            do
            {
                queryResult = db.Query("eventsByLatLng", new SpatialIndexQuery()
                {
                    QueryShape       = SpatialIndexQuery.GetQueryShapeFromLatLon(lat, lng, radius),
                    SpatialRelation  = SpatialRelation.Within,
                    SpatialFieldName = Constants.DefaultSpatialFieldName,
                    SortedFields     = new[]
                    {
                        new SortedField("Venue"),
                        new SortedField("__distance"),
                    }
                });
                if (queryResult.IsStale)
                {
                    Thread.Sleep(100);
                }
            } while (queryResult.IsStale);


            var expectedOrder = new[] { "Events/5", "Events/4", "Events/6", "Events/2", "Events/1", "Events/3", };

            Assert.Equal(expectedOrder.Length, queryResult.Results.Count);
            for (int i = 0; i < queryResult.Results.Count; i++)
            {
                Assert.Equal(expectedOrder[i], queryResult.Results[i].Value <RavenJObject>("@metadata").Value <string>("@id"));
            }
        }
Beispiel #11
0
 public SpatialCriteria WithinRadius(double radius, double latitude, double longitude)
 {
     return(RelatesToShape(SpatialIndexQuery.GetQueryShapeFromLatLon(latitude, longitude, radius), SpatialRelation.Within));
 }
Beispiel #12
0
 public SpatialCriteria WithinRadiusOf(double radius, double x, double y)
 {
     return(RelatesToShape(SpatialIndexQuery.GetQueryShapeFromLatLon(y, x, radius), SpatialRelation.Within));
 }
Beispiel #13
0
        public IndexQuery CreateTemplateQuery()
        {
            var transformer = SelectedTransformer.Value;

            if (transformer == "None" || !UseTransformer)
            {
                transformer = "";
            }

            var q = new IndexQuery
            {
                Query              = Query,
                DefaultOperator    = DefaultOperator,
                ResultsTransformer = transformer
            };

            if (SortBy != null && SortBy.Count > 0)
            {
                var sortedFields = new List <SortedField>();
                foreach (var sortByRef in SortBy)
                {
                    var sortBy = sortByRef.Value;
                    if (sortBy.EndsWith(QueryModel.SortByDescSuffix))
                    {
                        var field = sortBy.Remove(sortBy.Length - QueryModel.SortByDescSuffix.Length);
                        sortedFields.Add(new SortedField(field)
                        {
                            Descending = true
                        });
                    }
                    else
                    {
                        sortedFields.Add(new SortedField(sortBy));
                    }
                }
                q.SortedFields = sortedFields.ToArray();
            }

            if (ShowFields)
            {
                q.FieldsToFetch = new[] { Constants.AllFields }
            }
            ;

            q.DebugOptionGetIndexEntries = ShowEntries;

            q.SkipTransformResults = SkipTransformResults;



            if (IsSpatialQuerySupported && SpatialQuery.Y.HasValue && SpatialQuery.X.HasValue)
            {
                var radiusValue = SpatialQuery.Radius.HasValue ? SpatialQuery.Radius.Value : 1;

                q = new SpatialIndexQuery(q)
                {
                    QueryShape         = SpatialIndexQuery.GetQueryShapeFromLatLon(SpatialQuery.Y.Value, SpatialQuery.X.Value, radiusValue),
                    SpatialRelation    = SpatialRelation.Within,
                    SpatialFieldName   = SpatialQuery.FieldName,
                    DefaultOperator    = DefaultOperator,
                    RadiusUnitOverride = SpatialQuery.RadiusUnits
                };
            }

            return(q);
        }
Beispiel #14
0
 public SpatialCriteria WithinRadius(double radius, double latitude, double longitude, double distErrorPercent = 0.025)
 {
     return(RelatesToShape(SpatialIndexQuery.GetQueryShapeFromLatLon(latitude, longitude, radius), SpatialRelation.Within, distErrorPercent));
 }