How to get geolocation under nested attribute?

I have X number of sellers, but some sellers sell in two or more locations. So, every seller may have one, two or three locations:

"name": "John Doe",
"locations" : {
    "address": "Street 243"
    "_geoloc": {
        "lat": 40.639751,
        "lng": -73.778925
    }
}, {
    "address": "Avenue 222"
    "_geoloc": {
        "lat": 32.35454,
        "lng": -73.778925
    }
}

The problem arises when I use geolocation; Algolia always throw 0 results when I set even the same lat & lngof the location, from inside the Algolia webapp.

My guess is that _geoloc shouldn’t be nested but that’s impossible, as the seller doesn’t have location by his own.

Confirmed, the attribute _geoloc cannot be nested under another attribute on the record. If it’s done this way, Algolia won’t search by geolocation, so no results will be pushed to the client.

One way to takle this problem is to copy the _geoloc from your record to the root of your attributes if you need that information on both places.

Hello,

You’re right that the _geoloc attribute can only be set at the root element. In your case, because you have several locations per records, you have two ways of solving the issue:

  1. You can define _geoloc as an array of objects instead of a single object:
"_geoloc": [
  { "lat": 47.279430, "lng": 5.106450 },
  { "lat": 47.293228, "lng": 5.004570 },
  { "lat": 47.316669, "lng": 5.016670 }
]

This is the easiest solution, but you will lose the context of the address field on each geoloc.

  1. Instead of creating one record per user, you can create one record per address, and then group them using our distinct feature.

Your records would look something like this:

[
  {
    "name": "John Doe",
    "user_id": 42,
    "location": {
      "address": "Street 243"
    },
    "_geoloc": {
      "lat": 40.639751,
      "lng": -73.778925
    }
  },
  {
    "name": "John Doe",
    "user_id": 42,
    "location": {
      "address": "Avenue 222"
    },
    "_geoloc": {
      "lat": 32.35454,
      "lng": -73.778925
    }
  }
]

Each record contain a duplicate of the user information as well as its unique address + geoloc. By defining attributeForDistinct to user_id you’ll make sure only the most relevant result corresponding to this user will ever get returned.

It will add a bit more complexity to your records and will also increase the number of records you’ll have, but will let you keep the context of each geoloc.

Hope that helps,

1 Like

Thanks. I think I will use the first option as it’s more simple.