4
@JsonSerialize
@Document(collection = "fence")
@CompoundIndexes({
        @CompoundIndex(name = "loc_groupId_idx", 
                       def = "{ 'loc': 2dsphere, 'groups.groupId': 1 }",      
                       unique = false) })
public class GeofenceMongoVO {

  public GeofenceMongoVO() {}

  @Id
  private String fenceId;

  @Field
  private Long customerId;

  @Field
  private String fenceName;

  @Field
  private Byte type;

This is how I tried to ensure a compound index on a geospatial field and a field of a child document(groupId). But this is not working unfortunately. Is there a way by which I can ensure 2dsphere index from java code via annotations?

Sabya
  • 197
  • 4
  • 17
  • 1
    You have a typo, that's why it does not work. Should be `"{ 'loc': '2dsphere', 'groups.groupId': 1 }"` with quotes `''` around the "2dsphere". – Neil Lunn Jun 28 '17 at 10:29

2 Answers2

7

As of Spring Data MongoDB 1.10.10.RELEASE, you can annotate any field, whether it be at the document root or in a subdocument with:

@GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE)
private GeoJsonPoint myGeometry;
user5365075
  • 2,094
  • 2
  • 25
  • 42
2

I'm not sure if it can be done with annotations yet, but I found a blog post here where they do it with an ensureIndex. Something like th

@Autowired
MongoTemplate template;

public void setupIndex()
{
    template.indexOps(Location.class).ensureIndex( new GeospatialIndex("position") );
}
p.streef
  • 3,652
  • 3
  • 26
  • 50