简体   繁体   中英

Mongoengine geo spatial query with text search does not work as expected

The following is my query:

items = Item.objects(
                    location__near=[item_obj.longitude, item_obj.latitude],
                    location__max_distance=item_obj.range,
                    status__status=ITEM_STATUS_DISPLAYED
                ).filter(
                    Q(title__icontains=item_obj.search) |
                    Q(description__icontains=item_obj.search
                )
            ).hint([('location', '2dsphere')])

This query does not seem to work as objects outside the range is getting returned. And the item status also seems to be ignored. The range is given in meters.

The strange thing is the following query works without any issues:

items = Item.objects(
                    location__near=[item_obj.longitude, item_obj.latitude],
                    location__max_distance=item_obj.range,
                    status__status=ITEM_STATUS_DISPLAYED
                )

I am not sure what is wrong.

I recommend that you stay away from the $near handle since mongoengine is using a deprecated call to PyMongo and your application will fail if you update mongoDB to the latest version.

What I did was to use the geo_within query, specifically the geo_within_sphere since I am finding points within a circle around locations on earth. You can find reference here: MongoEngine geo query

One thing that they don't explain in there is converting the radius. If you use Km then you have to do radius/6371.0 if you use miles then radius/3959.0

My queries look like this:

data = data_set.objects(
           location__geo_within_sphere=[[longitude, latitude], radius/6371.0]
       )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM