Flutter数据库管理插件harndb的使用

发布于 1周前 作者 sinazl 来自 Flutter

Flutter数据库管理插件harndb的使用

HarnDB 简介

HarnDB 是一个用 Dart 编写的面向对象的文档数据库。它允许存储数据,并提供了用于执行读写操作的 API。

HarnDB 使用磁盘文件来存储数据,并完全在应用程序内存中运行,这使其适用于需要快速高效存储的应用程序。它还支持字段索引以加速查询,并提供了对数据进行聚合操作的接口。

简而言之,HarnDB 是一个简单、快速且易于使用的数据库,特别适合处理 JSON 格式的数据并需要快速高效存储的应用程序。

开始使用 HarnDB

要开始使用 HarnDB,首先需要在项目中导入 harndb 包,并创建一个 Harn 实例。

import 'package:harndb/harndb.dart';

void main() async {
  final harn = Harn();
  await harn.initialize();
}

初始化后,你可以创建一个集合并开始添加文档。

import 'package:harndb/harndb.dart';

void main() async {
  final harn = Harn();
  await harn.initialize();

  final myCollection = harn.collection('myCollection');

  final myDocument = {'name': 'John Doe', 'age': 30};

  await myCollection.insert(myDocument);
}

集合

在 HarnDB 中,集合类似于关系型数据库中的表或 NoSQL 数据库中的集合。它是相关联的 JSON 文档的容器。

每个集合在 HarnDB 中都有一个唯一的名称,并包含可以插入、更新、删除和查询的 JSON 文档。此外,集合还可以有一个或多个索引,这些索引可以使查询更有效。

Harn db = Harn();
final myFirstCollection = db.collection("myFirstCollection");

要创建一个集合,你需要实例化一个 Harn 对象并调用 collection 方法,传入你想要创建的集合的名称。

方法 Insert()

insert 方法允许将新文档添加到当前 HarnCollection 实例表示的集合中。要插入的文档必须是一个字符串键和动态值的映射,其中 _id 键不得存在,因为该方法会自动生成。

Future<void> insert(Map<String, dynamic> document) async

参数

参数 描述
document 包含新文档字段的映射。

返回

类型 描述
Future 一旦文档插入完成,该方法将解析为 void
Harn db = Harn();
final myCollection = db.collection('users');
await collection.insert({
  'name': 'John Doe',
  'age': 30,
  'email': 'johndoe@example.com',
});

方法 InsertMany()

insertMany 方法允许一次性向集合中插入多个文档。

insertMany(List<Map<String, dynamic>> documents) => Future<void>

参数

参数 描述
documents 包含要插入到集合中的文档的映射列表。

返回

类型 描述
Future 一旦文档插入完成,该方法将解析为 void
Harn db = Harn();
final collection = db.collection('users');

// 定义要插入集合中的文档列表
final documents = [
  {
    'firstName': 'John',
    'lastName': 'Doe',
    'email': 'john.doe@example.com',
  },
  {
    'firstName': 'Jane',
    'lastName': 'Doe',
    'email': 'jane.doe@example.com',
  },
  {
    'firstName': 'Bob',
    'lastName': 'Smith',
    'email': 'bob.smith@example.com',
  },
];

// 将文档插入集合
await collection.insertMany(documents);

方法 Find()

find 方法用于根据特定查询条件搜索集合中的文档。

List<Map<String, dynamic>> find(Map<String, dynamic> query)

参数

参数 描述
query 一个键值对映射,表示搜索查询。

返回

类型 描述
List<Map<String, dynamic>> 包含与搜索查询匹配的集合文档的映射列表。
Harn db = Harn();
final collection = db.collection('users');
// 插入一些文档
await collection.insert({'name': 'Alice', 'age': 25});
await collection.insert({'name': 'Bob', 'age': 30});
await collection.insert({'name': 'Charlie', 'age': 35});

// 搜索符合查询的文档
final results1 = collection.find({'name': 'Bob'}); // [{"_id": "...", "name": "Bob", "age": 35}]
final results2 = collection.find({'age': {'\$gt': 30}}); // [{"_id": "...", "name": "Bob", "age": 35}, {"_id": "...", "name": "Charlie", "age": 42}]

方法 FindOne()

findOne 方法用于查找并返回符合特定条件的第一个文档。

Map<String, dynamic>? findOne(bool Function(dynamic) predicate)

参数

参数 描述
predicate 接收一个文档并返回布尔值的谓词函数。

返回

类型 描述
Map<String, dynamic> 或 null 符合搜索条件的第一个文档的映射,如果没有找到文档则返回 null。
Harn db = Harn();
// 创建一个新的集合
final collection = db.collection('users');

// 插入一些文档
await collection.insert({'name': 'Alice', 'age': 28});
await collection.insert({'name': 'Bob', 'age': 35});
await collection.insert({'name': 'Charlie', 'age': 42});

// 查找符合搜索条件的第一个文档
final result1 = collection.findOne((document) => document['name'] == 'Bob'); // {"_id": "...", "name": "Bob", "age": 35}
final result2 = collection.findOne((document) => document['age'] > 30); // {"_id": "...", "name": "Bob", "age": 35}

方法 FindById()

findById 方法用于通过其唯一标识符 _id 在集合中查找文档。如果文档不存在于集合中,则返回 null。

Map<String, dynamic> findById(String id)

参数

参数 描述
id 要查找的文档的 _id

返回

类型 描述
Map<String, dynamic> 具有指定 _id 的文档,如果不存在则返回 null。
Harn db = Harn();
final collection = db.collection('users');
await collection.insert({
  'name': 'John',
  'age': 35,
});
final document = collection.findById('dnb3j77xus776sgb4j37s');
print(document); // { '_id': 'dnb3j77xus776sgb4j37s', 'name': 'John', 'age': 35, 'createdAt': 1649207692814, 'updatedAt': 1649207692814 }

方法 Count()

count 方法返回集合中存储的文档总数。

int count({Map<String, dynamic>? query})

参数

参数 描述
query 包含要搜索的文档字段和值的映射。如果不提供查询,则计数所有文档。

返回

类型 描述
int 与查询匹配的文档数量,或者如果没有提供查询,则为集合中的文档总数。
Harn db = Harn();
final users = db.collection('users');
users.insert({"name": "John", "age": 30});
users.insert({"name": "Jane", "age": 25});
users.insert({"name": "Bob", "age": 40});

// 计算集合中文档的数量
int documentCount = collection.count();
print(documentCount); // 3

// 计算集合中符合查询的文档数量
int matchingDocumentCount = collection.count(query: {"age": 30});
print(matchingDocumentCount); // 1

方法 Where()

where 方法用于根据给定条件过滤集合中的文档。

List<Map<String, dynamic>> where(bool Function(dynamic) predicate)

参数

参数 描述
predicate 接收一个值并返回布尔值的谓词函数。

返回

类型 描述
List<Map<String, dynamic>> 符合谓词条件的文档列表。
Harn db = Harn();
final users = db.collection('users');
// 向集合中添加一些用户。
await users.insert({'name': 'Alice', 'age': 30, 'city': 'New York'});
await users.insert({'name': 'Bob', 'age': 25, 'city': 'San Francisco'});
await users.insert({'name': 'Charlie', 'age': 35, 'city': 'Los Angeles'});

// 获取年龄大于25岁的用户。
final result = users.where((doc) => doc['age'] > 25);

print(result);
// 输出: [{'name': 'Alice', 'age': 30, 'city': 'New York'}, {'name': 'Charlie', 'age': 35, 'city': 'Los Angeles'}]

方法 Update()

update 方法用于更新集合中的现有文档。

Future<void> update(String id, Map<String, dynamic> updates) async

参数

参数 描述
id 要更新的文档的唯一标识符。
updates 包含要更新的字段和值的映射。

返回

类型 描述
Future 一旦文档更新完成,该方法将解析为 void
Harn db = Harn();
final collection = db.collection('users');
await collection.insert({
  'name': 'John Doe',
  'age': 30,
});

// 更新 ID 为 'jh4y67s62hh26s6534u47s6s' 的文档
await collection.update('jh4y67s62hh26s6534u47s6s', {
  'name': 'Jane Doe',
  'age': 35,
});

方法 Remove()

remove 方法用于从集合中删除文档。

Future<void> remove(String id) async

参数

参数 描述
id 要删除的文档的唯一标识符。

返回

类型 描述
Future 一旦文档被删除,该方法将解析为 void
Harn db = Harn();
final collection = db.collection('my_collection');
await collection.insert({'name': 'John', 'age': 30});
await collection.remove('jh4y67s62hh26s6534u47s6s');

方法 DeleteMany()

deleteMany 方法用于基于查询删除集合中的多个文档。

Future<void> deleteMany(Map<String, dynamic> query) async

参数

参数 描述
query 表示要删除的文档的查询映射。

返回

类型 描述
Future 一旦文档被删除,该方法将解析为 void
Harn db = Harn();
final usersCollection = db.collection('users');
// 删除所有年龄为30的文档
await usersCollection.deleteMany({'age': 30});

方法 UpdateMany()

updateMany 方法用于基于查询更新集合中的多个文档。

Future<void> updateMany(Map<String, dynamic> query, Map<String, dynamic> updates) async

参数

参数 描述
query 包含要更新的文档字段和值的映射。
updates 包含要更新的字段和值的映射。

返回

类型 描述
Future 一旦文档更新完成,该方法将解析为 void
Harn db = Harn();
final users = db.collection('users');
// 假设我们有一个包含"name", "age" 和 "city" 字段的用户集合
// 将所有住在 "Barcelona" 的用户的年龄更新为30岁
await users.updateMany({'city': 'Barcelona'}, {'age': 30});

方法 Distinct()

distinct 方法用于获取集合中文档特定字段的唯一值。

List<dynamic> distinct(String fieldName)

参数

参数 描述
fieldName 要提取唯一值的字段名称。

返回

类型 描述
List 包含唯一值的字段值列表。
Harn db = Harn();
final collection = db.collection('users');
collection.insert({'title': 'El Aleph', 'author': 'Jorge Luis Borges'});
collection.insert({'title': 'Cien años de soledad', 'author': 'Gabriel García Márquez'});
collection.insert({'title': 'La tregua', 'author': 'Mario Benedetti'});
collection.insert({'title': 'Ficciones', 'author': 'Jorge Luis Borges'});

final uniqueAuthors = collection.distinct('author');
print(uniqueAuthors); // ['Jorge Luis Borges', 'Gabriel García Márquez', 'Mario Benedetti']

方法 GroupBy()

groupBy 方法用于根据特定字段对集合中的文档进行分组。

Map<dynamic, List<Map<String, dynamic>>> groupBy(String fieldName)

参数

参数 描述
fieldName 用于分组的字段名称。

返回

类型 描述
Map 包含唯一值及其相关文档列表的映射。
Harn db = Harn();
final users = db.collection('users');
users.insert({'name': 'John', 'age': 25, 'gender': 'Male'});
users.insert({'name': 'Jane', 'age': 30, 'gender': 'Female'});
users.insert({'name': 'Bob', 'age': 35, 'gender': 'Male'});
users.insert({'name': 'Alice', 'age': 40, 'gender': 'Female'});
users.insert({'name': 'David', 'age': 45, 'gender': 'Male'});

final groups = users.groupBy('gender');

输出将是按性别分组的文档:

{
  'Male': [
    {'name': 'John', 'age': 25, 'gender': 'Male'},
    {'name': 'Bob', 'age': 35, 'gender': 'Male'},
    {'name': 'David', 'age': 45, 'gender': 'Male'},
  ],
  'Female': [
    {'name': 'Jane', 'age': 30, 'gender': 'Female'},
    {'name': 'Alice', 'age': 40, 'gender': 'Female'},
  ],
}

方法 AggregateCount()

aggregateCount 方法用于计算集合中文档特定字段的不同值的数量。

Map<dynamic, int> aggregateCount(String fieldName)

参数

参数 描述
fieldName 要计算不同值数量的字段名称。

返回

类型 描述
Map 包含不同值及其出现次数的映射。
Harn db = Harn();
final collection = db.collection('people');
await collection.insert({'name': 'Alice', 'age': 25, 'gender': 'female'});
await collection.insert({'name': 'Bob', 'age': 30, 'gender': 'male'});
await collection.insert({'name': 'Charlie', 'age': 20, 'gender': 'male'});
await collection.insert({'name': 'Diana', 'age': 28, 'gender': 'female'});
await collection.insert({'name': 'Eve', 'age': 35, 'gender': 'female'});

final genderCounts = collection.aggregateCount('gender');
print(genderCounts); // {female: 3, male: 2}

方法 Index()

index 方法用于为集合中的特定字段创建索引。

void index(String fieldName)

参数

参数 描述
fieldName 要创建索引的字段名称。

返回

类型 描述
创建索引。
Harn db = Harn();
final users = db.collection('users');

// 插入一些文档...

users.index('email');

// 一旦创建了索引,我们可以根据特定的电子邮件值查找文档:

final List<String> userIds = users.collection['email-index']['example@example.com'];
final List<Map<String, dynamic>> usersWithEmail = List<Map<String, dynamic>>.from(userIds.map((id) => users.findById(id)));

方法 OrderBy()

orderBy 方法用于根据特定字段对集合中文档进行排序。

List<Map<String, dynamic>> orderBy(String field, {bool descending = false})

参数

参数 描述
field 按其排序的字段名称。
descending 是否按降序排序,默认为 false

返回

类型 描述
List<Map<String, dynamic>> 根据字段排序后的文档列表。
Harn db = Harn();
final collection = db.collection('users');
collection.insert({'name': 'Alice', 'age': 25});
collection.insert({'name': 'Bob', 'age': 35});
collection.insert({'name': 'Charlie', 'age': 30});

// 按年龄升序排序
final documentsAsc = collection.orderBy('age');
print(documentsAsc);
// 结果: [{'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 30}, {'name': 'Bob', 'age': 35}]

// 按年龄降序排序
final documentsDesc = collection.orderBy('age', descending: true);
print(documentsDesc);
// 结果: [{'name': 'Bob', 'age': 35}, {'name': 'Charlie', 'age': 30}, {'name': 'Alice', 'age': 25}]

方法 WhereBetween()

whereBetween 方法用于根据特定字段的值范围过滤集合中的文档。

List<Map<String, dynamic>> whereBetween(String field, dynamic start, dynamic end)

参数

参数 描述
field 要搜索值范围的字段名称。
start 搜索范围的下限。
end 搜索范围的上限。

返回

类型 描述
List<Map<String, dynamic>> 包含符合范围条件的文档列表。
Harn db = Harn();
final harnCollection = db.collection('users');

await harnCollection.insert({
    'name': 'John Doe',
    'age': 35,
});

await harnCollection.insert({
    'name': 'Jane Smith',
    'age': 25,
});

await harnCollection.insert({
    'name': 'Bob Johnson',
    'age': 45,
});

final List<Map<String, dynamic>> result = harnCollection.whereBetween('age', 30, 40);

print(result);

// 预期输出:
// [
//   {'name': 'John Doe', 'age': 35, '_id': '0', 'createdAt': 1649243610000, 'updatedAt': 1649243610000},
// ]

方法 Calculate()

calculate 方法用于对集合中文档特定字段的值执行简单的算术运算。

List<Map<String, dynamic>> calculate(String field, num value, {String operator = '+'})

参数

参数 描述
field 要计算的字段名称。
value 要使用的值。
operator 运算符,默认为 +

返回

类型 描述
List<Map<String, dynamic>> 包含更新后的文档列表。
Harn db = Harn();
final ventasCollection = db.collection('ventas');
await ventasCollection.insert({'monto': 100});
await ventasCollection.insert({'monto': 200});
await ventasCollection.insert({'monto': 300});

final nuevosMontos = ventasCollection.calculate('monto', 50, operator: '+');

方法 FindExtremes()

findExtremes 方法用于查找集合中文档特定字段的最大值和最小值。

Map<String, num> findExtremes(String field)

参数

参数 描述
field 要查找最大值和最小值的字段名称。

返回

类型 描述
Map<String, num> 包含最大值和最小值的映射。
Harn db = Harn();
final collection = db.collection('myCollection');
collection.insert({'name': 'Alice', 'age': 35});
collection.insert({'name': 'Bob', 'age': 30});
collection.insert({'name': 'Charlie', 'age': 40});

final extremes = collection.findExtremes('age');

if (extremes != null) {
  print('最小值: ${extremes["min"]}');
  print('最大值: ${extremes["max"]}');
} else {
  print('未找到符合条件的文档。');
}

方法 SumField()

sumField 方法用于计算集合中文档特定字段的总和。

num sumField(String field)

参数

参数 描述
field 要计算总和的字段名称。

返回

类型 描述
num 字段的总和。
Harn db = Harn();
final harnCollection = db.collection('users');
await harnCollection.insert({'name': 'Alice', 'age': 25});
await harnCollection.insert({'name': 'Bob', 'age': 30});
await harnCollection.insert({'name': 'Charlie', 'age': 35});

final sumOfAges = harnCollection.sumField('age');
print(sumOfAges); // 输出: 90

方法 AverageField()

averageField 方法用于计算集合中文档特定字段的平均值。

num averageField(String field)

参数

参数 描述
field 要计算平均值的字段名称。

返回

类型 描述
num 字段的平均值。
Harn db = Harn();
final harn = db.collection('estudiantes');
await harn.insert({'nombre': 'Juan', 'nota': 8});
await harn.insert({'nombre': 'Ana', 'nota': 9});
await harn.insert({'nombre': 'Pedro', 'nota': 7});

final promedioNotas = harn.averageField('nota');
print('El promedio de las notas es $promedioNotas');

方法 FindByDate()

findByDate 方法用于查找具有特定日期的文档。

List<Map<String, dynamic>> findByDate(
    DateTime date, {
    bool includeCreatedAt = true,
    bool includeUpdatedAt = false,
    DateSearchType searchType = DateSearchType.exact
  })

参数

参数 描述
date 要搜索的日期。
includeCreatedAt 是否包括创建时间,默认为 true
includeUpdatedAt 是否包括更新时间,默认为 false
searchType 搜索类型,默认为 DateSearchType.exact

返回

类型 描述
List<Map<String, dynamic>> 包含符合日期条件的文档列表。
Harn db = Harn();
final collection = db.collection('my_collection');

// 添加一些带有创建时间和更新时间的文档
final now = DateTime.now();
final yesterday = now.subtract(Duration(days: 1));
final tomorrow = now.add(Duration(days: 1));
collection.insert({'createdAt': now, 'updatedAt': now, 'name': 'Document 1'});
collection.insert({'createdAt': yesterday, 'updatedAt': yesterday, 'name': 'Document 2'});
collection.insert({'createdAt': tomorrow, 'updatedAt': tomorrow, 'name': 'Document 3'});

// 查找今天创建的文档
final todayDocuments = collection.findByDate(now);
print(todayDocuments); // [{createdAt: 2023-04-07 11:26:48.201202, updatedAt: 2023-04-07 11:26:48.201202, name: Document 1}]

// 查找昨天之后创建或更新的文档
final afterYesterdayDocuments = collection.findByDate(yesterday, searchType: DateSearchType.after);
print(afterYesterdayDocuments); // [{createdAt: 2023-04-07 11:26:48.201202, updatedAt: 2023-04-07 11:26:48.201202, name: Document 1}, {createdAt: 2023-04-08 11:26:48.201202, updatedAt: 2023-04-08 11:26:48.201202, name: Document 3}]

// 查找明天之前创建或更新的文档
final beforeTomorrowDocuments = collection.findByDate(tomorrow, includeUpdatedAt: true, searchType: DateSearchType.before);
print(beforeTomorrowDocuments); // [{createdAt: 2023-04-07 11:26:48.201202, updatedAt: 2023-04-07 11:26:48.201202, name: Document 1}, {createdAt: 2023-04-06 11:26:48.201202, updatedAt: 2023-04-06 11:26:48.201202, name: Document 2}]

方法 OrderByDate()

orderByDate 方法用于根据日期对集合中的文档进行排序。

List<Map<String, dynamic>> orderByDate({String fieldName = 'createdAt', bool descending = false})

参数

参数 描述
fieldName 用于排序的字段名称,默认为 createdAt
descending 是否按降序排序,默认为 false

返回

类型 描述
List<Map<String, dynamic>> 根据日期排序后的文档列表。
Harn db = Harn();
final collection = db.collection('my_collection');

collection.insert({
  'title': 'Document 1',
  'body': 'This is the first document',
  'createdAt': DateTime(2022, 1, 1),
  'updatedAt': DateTime(2022, 1, 1),
});

collection.insert({
  'title': 'Document 2',
  'body': 'This is the second document',
  'createdAt': DateTime(2022, 1, 3),
  'updatedAt': DateTime(2022, 1, 3),
});

collection.insert({
  'title': 'Document 3',
  'body': 'This is the third document',
  'createdAt': DateTime(2022, 1, 2),
  'updatedAt': DateTime(2022, 1, 2),
});

// 按创建日期降序排序
final sortedDocuments = collection.orderByDate(fieldName: 'createdAt', descending: true);

// 打印排序后的文档
sortedDocuments.forEach((document) {
  print(document);
});

方法 GeoSearch()

geoSearch 方法用于根据地理位置搜索集合中的文档。

List<Map<String, dynamic>> geoSearch(String field, double lat, double lng, double radius)

参数

参数 描述
field 用于地理搜索的字段名称。
lat 搜索的纬度。
lng 搜索的经度。
radius 搜索的半径(公里)。

返回

类型 描述
List<Map<String, dynamic>> 包含符合地理位置条件的文档列表。
Harn db = Harn();
final users = db.collection('users');

users.insert({
  'name': 'John Doe',
  'location': {'lat': 51.5074, 'lng': -0.1278}
});
users.insert({
  'name': 'Jane Doe',
  'location': {'lat': 40.7128, 'lng': -74.0060}
});

// 查找距离特定位置1000公里内的文档
final List<Map<String, dynamic>> result = users.geoSearch('location', 37.7749, -122.4194, 1000);

方法 RandomDocument()

randomDocument 方法用于获取集合中文档的随机记录。

Map<String, dynamic>? randomDocument(Map<String, dynamic> query)

参数

参数 描述
query 查询映射。

返回

类型 描述
Map<String, dynamic> 包含符合条件的随机文档。
Harn db = Harn();
final collection = db.collection('my_collection');

// 向集合中插入一些文档
await collection.insert({'name': 'John', 'age': 30});
await collection.insert({'name': 'Alice', 'age': 25});
await collection.insert({'name': 'Bob', 'age': 35});

// 获取符合查询条件的随机文档
final query = {'age': {'\$gt': 18}};
final randomDoc = collection.randomDocument(query);
if (randomDoc != null) {
  print('随机选择的文档: $randomDoc');
} else {
  print('未找到符合条件的文档。');
}

方法 CountWhere()

countWhere 方法用于计算集合中符合特定条件的文档数量。

int countWhere(bool Function(dynamic) predicate)

参数

参数 描述
predicate 接收一个文档并返回布尔值的谓词函数。

返回

类型 描述
int 符合条件的文档数量。
Harn db = Harn();
final users = db.collection('users');
users.insert({'name': 'John Doe', 'age': 25, 'gender': 'male'});
users.insert({'name': 'Jane Doe', 'age': 30, 'gender': 'female'});
users.insert({'name': 'Bob Smith', 'age': 20, 'gender': 'male'});
users.insert({'name': 'Alice Johnson', 'age': 35, 'gender': 'female'});

// 计算男性用户数量
final count = users.countWhere((document) => document['gender'] == 'male');
print(count); // 输出: 2

方法 Subscribe()

subscribe 方法用于向集合添加观察者。

void subscribe(HarnObserverCollection observer)

参数

参数 描述
observer HarnObserverCollection 实例。
Harn db = Harn();
final collection = db.collection('users');
final observer = MyObserver(); // 实现 `HarnObserverCollection` 接口的类
collection.subscribe(observer);

方法 Unsubscribe()

unsubscribe 方法用于从集合中移除观察者。

void unsubscribe(HarnObserverCollection observer)

参数

参数 描述
observer HarnObserverCollection 实例。
Harn db = Harn();

// 创建一个集合对象
final collection = db.collection('employees');

// 创建一个观察者对象
final observer = MyObserver();

// 订阅观察者到集合
collection.subscribe(observer);

// ...

// 从集合中取消订阅观察者
collection.unsubscribe(observer);

方法 FullTextSearch()

fullTextSearch 方法用于在集合中执行全文搜索。

List<Map<String, dynamic>> fullTextSearch(String query)

参数

参数 描述
query 搜索查询。

返回

类型 描述
List<Map<String, dynamic>> 包含符合全文搜索条件的文档列表。
Harn db = Harn();
final myCollection = db.collection('my_collection');

await myCollection.insert({
  'title': 'The quick brown fox',
  'body': 'Jumped over the lazy dog'
});

await myCollection.insert({
  'title': 'The lazy dog',
  'body': 'Just laid there'
});

final searchResults = myCollection.fullTextSearch('lazy dog');

// `searchResults` 变量将包含以下元素的列表:
// [
//   {
//     '_id': '1',
//     'title': 'The quick brown fox',
//     'body': 'Jumped over the lazy dog',
//     'createdAt': 1649257268503,
//     'updatedAt': 1649257268503
//   },
//   {
//     '_id': '2',
//     'title': 'The lazy dog',
//     'body': 'Just laid there',
//     'createdAt': 1649257287319,
//     'updatedAt': 1649257287319
//   }
// ]

方法 Join()

join 方法用于将两个集合的文档合并。

List<Map<String, dynamic>> join(
  HarnCollection collectionB,
  String joinField, {
  List<String> propertiesA = const [],
  List<String> propertiesB = const []
})

更多关于Flutter数据库管理插件harndb的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter数据库管理插件harndb的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用harndb插件进行数据库管理的代码示例。harndb是一个用于Flutter的轻量级数据库管理插件,它提供了方便的API来进行数据库操作。不过需要注意的是,由于harndb并不是一个广为人知的插件(可能是一个假想的或特定的项目插件),以下代码示例将基于一个假设的API设计。如果你使用的harndb插件有不同的API,请根据官方文档进行调整。

首先,确保你已经在pubspec.yaml文件中添加了harndb依赖:

dependencies:
  flutter:
    sdk: flutter
  harndb: ^x.y.z  # 替换为实际的版本号

然后,运行flutter pub get来安装依赖。

接下来,是一个简单的Flutter应用示例,展示如何使用harndb进行数据库操作:

import 'package:flutter/material.dart';
import 'package:harndb/harndb.dart';  // 假设harndb的import路径

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Harndb Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Harndb Demo'),
        ),
        body: Center(
          child: MyDatabaseDemo(),
        ),
      ),
    );
  }
}

class MyDatabaseDemo extends StatefulWidget {
  @override
  _MyDatabaseDemoState createState() => _MyDatabaseDemoState();
}

class _MyDatabaseDemoState extends State<MyDatabaseDemo> {
  late HarndbDatabase _db;

  @override
  void initState() {
    super.initState();
    // 初始化数据库连接
    _db = HarndbDatabase.open('my_database.db');
    // 创建表(假设harndb支持SQL语句)
    _db.execute('''
      CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        age INTEGER NOT NULL
      )
    ''');
  }

  @override
  void dispose() {
    // 关闭数据库连接
    _db.close();
    super.dispose();
  }

  Future<void> _insertUser() async {
    var result = await _db.rawInsert('''
      INSERT INTO users (name, age) VALUES (?, ?)
    ''', ['Alice', 30]);
    print('Insert result: $result');
  }

  Future<List<Map<String, dynamic>>> _queryUsers() async {
    var result = await _db.rawQuery('SELECT * FROM users');
    return result;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        ElevatedButton(
          onPressed: () async {
            await _insertUser();
            setState(() {}); // 触发UI更新(如果需要)
          },
          child: Text('Insert User'),
        ),
        ElevatedButton(
          onPressed: () async {
            var users = await _queryUsers();
            print('Users: $users');
            // 这里可以根据users数据更新UI,例如显示在ListView中
          },
          child: Text('Query Users'),
        ),
      ],
    );
  }
}

// 假设HarndbDatabase类提供的方法如下(根据harndb的实际API调整)
class HarndbDatabase {
  // 假设的数据库连接对象
  final Object _dbConnection;

  HarndbDatabase._(this._dbConnection);

  // 打开数据库连接
  static Future<HarndbDatabase> open(String path) async {
    // 这里应该是实际的数据库打开逻辑
    var connection = Object(); // 假设的连接对象
    return HarndbDatabase._(connection);
  }

  // 执行SQL语句(不返回结果)
  Future<void> execute(String sql, [List<Object?>? args]) async {
    // 执行SQL语句的逻辑
  }

  // 执行SQL查询并返回结果
  Future<List<Map<String, dynamic>>> rawQuery(String sql, [List<Object?>? args]) async {
    // 执行查询并返回结果的逻辑
    return []; // 假设返回空列表
  }

  // 执行SQL插入并返回插入的ID
  Future<int> rawInsert(String sql, [List<Object?>? args]) async {
    // 执行插入并返回ID的逻辑
    return 0; // 假设返回0
  }

  // 关闭数据库连接
  void close() {
    // 关闭数据库连接的逻辑
  }
}

请注意,上述代码中的HarndbDatabase类及其方法(如openexecuterawQueryrawInsertclose)是基于假设的,因为harndb插件的具体API未知。在实际使用中,你需要根据harndb插件的官方文档来调整这些方法和类的实现。

此外,由于harndb可能不是一个广泛使用的插件,因此你可能需要查找其官方仓库或文档来获取准确的API信息和用法示例。如果harndb实际上是一个特定的内部或私有插件,那么你可能需要联系插件的维护者或参考相关的内部文档。

回到顶部