MongoDB学习日记 - java代码(六):索引 index

本文深入探讨了MongoDB的索引机制,包括普通索引和文本索引的创建与使用方法,并展示了如何利用文本索引进行高效全文检索。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里的示例代码都是简要代码,详细代码可以参考我打包好的代码,地址:百度云 mongo-demo.rar

MongoDB 的索引太复杂了,这里就介绍下,基本够用;如果有开发需求,那么你还是仔细看看,功能还是很强大的,例如:地理位置索引等。

MongoClient client = new MongoClient();
MongoDatabase database = client.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("test");

// 语法解释 :db.test.createIndex({"i":1})
collection.createIndex(new Document("i",1)); // 创建普通索引

// 语法解释 :db.test.createIndex({"content":"text"})
collection.createIndex(new Document("content","text")); // 创建文本索引

ListIndexesIterable<Document> list = collection.listIndexes();
for (Document document : list) {
    System.out.println(document.toJson());
}

client.close();

这里再讲讲文本索引的使用吧:

// 插入测试数据
/*collection.insertOne(new Document("_id", 0).append("content", "textual content"));
collection.insertOne(new Document("_id", 1).append("content", "additional content"));
collection.insertOne(new Document("_id", 2).append("content", "irrelevant content"));*/

long matchCount = collection.count(Filters.text("textual content -irrelevant"));
System.out.println("Text search matches: " + matchCount);

// Find using the $language operator
Bson textSearch = Filters.text("textual irrelevant", "english");
matchCount = collection.count(textSearch);
System.out.println("Text search matches (english): " + matchCount);

// Find the highest scoring match
Document projection = new Document("score", new Document("$meta", "textScore"));
Document myDoc = collection.find(textSearch).projection(projection).first();
System.out.println("Highest scoring document: " + myDoc.toJson());

(注:这段代码是从 MongoDB 官网 copy 下的代码。)

  • Filters.text() : 这是 MongoDB 的全文检索,通过文本索引来检索,语法解释如下(前面没讲):
db.runCommand("text", {search: "textual content -irrelevant"})

需要注意 "textual content -irrelevant" 这部分的意思是:通过创建的文本索引,查找所有包含 textual 和 content 而不包含 irrelevant 的 document(文档)。Filters.text("textual irrelevant", "english"); 的意思则是匹配 english,可以添加多个 Filters.text("textual irrelevant", "english Chinese"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值