mongodb的Multikey Indexes

来源:互联网 发布:网络维护考题 编辑:程序博客网 时间:2024/04/28 09:51

这是背景:

最近写了个小站,可以对图片进行tag,然后点击tag可以把有相同tag的图片列出来。运气好的是,我找到了Multikey Indexes。于是乎一切都简单了。

动手:

图片信息放入images这个collection,下面是其中一个image:

{
   "_id": ObjectId("506d35b537e904092948363a"),
   "_class": "com.wwt.cn.beauty.model.Image",
   "name": "Armani_56.jpg",
   "tags": {
     "0": "wq",
     "1": "d",
     "2": "你在做什么" 
  },
   "star": 0,
   "userName": "123",
   "date": ISODate("2012-10-04T07: 07: 33.479Z"),
   "url": "http: \/\/www.test.com\/pic_storage\/123\/Armani_56.jpg" 
}

1)加索引

mongoTemplate.ensureIndex(new Index().named("tag_index").on("tags", Order.ASCENDING), "image");

2)查找

List<Image> images= mongoTemplate.find(new Query(Criteria.where("tags").is(tagName)), Image.class);

问题解决。


解惑:看下mongodb的官方说明一下就清楚了,请猛击:http://docs.mongodb.org/manual/core/indexes/#index-type-multikey

贴部分说明 :

If you index a field that contains an array, MongoDB indexes each value in the array separately, in a “multikey index.”

Example

 

Given the following document:

{ "_id" : ObjectId("..."),  "name" : "Warm Weather",  "author" : "Steve",  "tags" : [ "weather", "hot", "record", "april" ] }

Then an index on the tags field would be a multikey index and would include these separate entries:

{ tags: "weather" }{ tags: "hot" }{ tags: "record" }{ tags: "april" }

Queries could use the multikey index to return queries for any of the above values.

mongodb在array上的索引直接使用multikey index,而multikey index将数组变成了多个拥有相同key的key-value对,找某一个tag,只要进行比较操作即可。

当然对于查找来说可以更简单。

更人性化些:

List<Image> images= imageRepository.findByTags(tagName);

更方便些:

Page<Image> images=imageRepository.findByTags(tagName, new PageRequest(0, 10));

原因是:

public interface ImageRepository extends PagingAndSortingRepository<Image, ObjectId> {

public List<Image> findByTags(String tags);
public Page<Image> findByTags(String tags,Pageable pageable);


}

原创粉丝点击