【问题标题】:create indexes for search using MongoTemplate?使用 MongoTemplate 创建搜索索引?
【发布时间】:2016-01-12 16:44:00
【问题描述】:

我们如何使用MongoTemplate 为以下查询创建Indexes?我指的是站点http://docs.mongodb.org/v2.4/tutorial/search-for-text/,他们没有提供任何关于我们如何使用 MongoTemplate 创建索引的详细信息?

db.getCollection('user').ensureIndex({ firstName: "text", middleName : 
"text", lastName : "text",emailId:"text" });

【问题讨论】:

    标签: mongodb spring-data-mongodb full-text-indexing mongotemplate


    【解决方案1】:

    假设您的实体 User 被建模为

    @Document
    class User {
        String firstName;
        String middleName;
        String lastName;
        String emailId;
    }
    

    如果想要有一个基于其 firstName、middleName、lastName 和 emailId 字段的文本索引,原始 MongoDB 索引定义将如下所示:

     { 
        firstName: "text", 
        middleName: "text", 
        lastName: "text",
        emailId: "text" 
    }
    

    create a text index在您想要启用全文搜索的字段上,执行以下操作

    TextIndexDefinition textIndex = new TextIndexDefinitionBuilder()
        .onField("firstName")
        .onField("middleName")
        .onField("lastName")
        .onField("emailId")
        .build();
    
    MongoTemplate mongoTemplate = new MongoTemplate(new Mongo(), "database"); // obtain MongoTemplate
    mongoTemplate.indexOps(User.class).ensureIndex(textIndex);
    

    也可以通过映射注解自动创建索引:

    @Document
    class User {
        @TextIndexed String firstName;
        @TextIndexed String middleName;
        @TextIndexed String lastName;
        @TextIndexed String emailId;
    }
    

    【讨论】:

      【解决方案2】:

      使用 Spring Java 在 mongo 中创建索引的最简单方法是:

      // Define ur mongo template defination
      
      DBObject indexOptions = new BasicDBObject();
      indexOptions.put("a", 1);
      indexOptions.put("b", 1);
      indexOptions.put("c.d", 1);
      indexOptions.put("e.f", 1);
      CompoundIndexDefinition indexDefinition =
                  new CompoundIndexDefinition(indexOptions);
      mongoTemplate.indexOps(<Classname>.class).ensureIndex(indexDefinition);
      

      可以在索引定义上配置唯一索引: mongoTemplate.indexOps(&lt;Classname&gt;.class).ensureIndex(indexDefinition.unique());

      【讨论】:

        【解决方案3】:

        在spring mongodb 2.0.1中

            TextIndexDefinition textIndex = new TextIndexDefinition.TextIndexDefinitionBuilder().onField(indexName).build();
        
            mongoTemplate.indexOps(DINMonitorLog.class).ensureIndex(textIndex);
        

        【讨论】:

          猜你喜欢
          • 2020-07-28
          • 2011-03-20
          • 1970-01-01
          • 2020-03-03
          • 2017-07-07
          • 2017-07-12
          • 2020-04-26
          • 2015-09-21
          • 1970-01-01
          相关资源
          最近更新 更多