我的Mongo数据库字段如下:
"_id" : ObjectId("51d582be7a8d51bd29ca78a3"),
"Filename" : "sample.pdfe",
"Title" : null,
"Author" : null,
"ContentType" : "application/x-msdownload; format=pe32",
"url" : "Z:sample.pdf",
"Keywords" : ["php","java",".net","python"]
下面是我在索引字段上进行全文搜索的代码
m = new Mongo("10.0.0.26", 27017);
DB db = m.getDB("soft") ;
DBCollection col = db.getCollection("metadatanew") ;
String collection = col.toString();
DBObject searchCmd = new BasicDBObject();
searchCmd.put("text", collection);
searchCmd.put("search", name);
CommandResult commandResult = db.command(searchCmd);
BasicDBList results = (BasicDBList)commandResult.get("results");
for (Iterator <Object> it = results.iterator();it.hasNext();)
{
BasicDBObject result = (BasicDBObject) it.next();
BasicDBObject dbo = (BasicDBObject) result.get("obj");
System.out.println(dbo.getString("Filename"));
}
我使用下面的命令在两个字段上创建Text索引:
db.metadatanew.ensureIndex({'Filename':"text"}, {'Keywords':"text"})
我已经在文件名和关键字上创建了文本索引,但我只能对文件名进行全文搜索,我的代码有什么问题,请帮帮我
答案 0 :(得分:4)
ensureIndex
函数的第二个参数是选项。您应该在两个字段上创建唯一索引:
db.metadatanew.ensureIndex( { "Keywords" : "text", "Filename" : "text"} )
查看更多:
http://docs.mongodb.org/manual/tutorial/create-text-index-on-multiple-fields/
答案 1 :(得分:2)
在两个字段上创建唯一索引的另一种方法:
BasicDBObject basicDBObject = new BasicDBObject();
basicDBObject.append("Keywords", "text");
basicDBObject.append("Filename", "text");
dbCollection.createIndex(basicDBObject);