-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
156 lines (129 loc) · 4.68 KB
/
example.py
File metadata and controls
156 lines (129 loc) · 4.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
#!/usr/bin/env python3
"""
Notsql ライブラリの使用例
"""
import sys
import os
# パスを追加
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from notsql import NotsqlDB
def main():
print("🚀 Notsql ライブラリの使用例")
print("=" * 50)
# データベース作成
db = NotsqlDB('example_db')
print("✅ データベース 'example_db' を作成しました")
# コレクション取得
users = db.collection('users')
posts = db.collection('posts')
print("✅ コレクション 'users' と 'posts' を取得しました")
# インデックス作成
users.create_index('email', unique=True)
posts.create_index('author_id')
print("✅ インデックスを作成しました")
# ユーザーデータ挿入
print("\n📝 ユーザーデータの挿入:")
user_ids = users.insert_many([
{
'name': 'Alice',
'email': 'alice@example.com',
'age': 30,
'tags': ['python', 'programming']
},
{
'name': 'Bob',
'email': 'bob@example.com',
'age': 25,
'tags': ['javascript', 'web']
},
{
'name': 'Charlie',
'email': 'charlie@example.com',
'age': 35,
'tags': ['python', 'data_science']
}
])
for i, user_id in enumerate(user_ids):
print(f" ユーザー {i+1}: {user_id}")
# 投稿データ挿入
print("\n📝 投稿データの挿入:")
post_ids = posts.insert_many([
{
'title': 'Python入門',
'content': 'Pythonの基本的な使い方について',
'author_id': user_ids[0],
'tags': ['python', 'tutorial'],
'status': 'published'
},
{
'title': 'JavaScript Tips',
'content': 'JavaScriptのコツを紹介',
'author_id': user_ids[1],
'tags': ['javascript', 'tips'],
'status': 'published'
},
{
'title': 'データ分析入門',
'content': 'データ分析の基本',
'author_id': user_ids[2],
'tags': ['python', 'data_science'],
'status': 'draft'
}
])
for i, post_id in enumerate(post_ids):
print(f" 投稿 {i+1}: {post_id}")
# 検索例
print("\n🔍 検索例:")
# 全ユーザー検索
all_users = users.find()
print(f" 全ユーザー数: {len(all_users)}")
# 条件付き検索
python_users = users.find({'tags': {'$in': ['python']}})
print(f" Pythonユーザー数: {len(python_users)}")
# 年齢順ソート
sorted_users = users.find({}, sort={'age': 1})
print(f" 年齢順ユーザー: {[u['name'] for u in sorted_users]}")
# 複雑なクエリ
adult_programmers = users.find({
'$and': [
{'age': {'$gte': 25}},
{'tags': {'$in': ['python', 'programming']}}
]
})
print(f" 25歳以上のプログラマー: {[u['name'] for u in adult_programmers]}")
# 公開済み投稿
published_posts = posts.find({'status': 'published'})
print(f" 公開済み投稿数: {len(published_posts)}")
# 更新例
print("\n📝 更新例:")
# 年齢を1つ増加
users.update_one({'name': 'Alice'}, {'$inc': {'age': 1}})
alice = users.find_one({'name': 'Alice'})
print(f" Alice の年齢: {alice['age']}")
# 投稿ステータスを更新
posts.update_one({'title': 'データ分析入門'}, {'$set': {'status': 'published'}})
print(" ドラフト投稿を公開に変更しました")
# 統計情報
print("\n📊 統計情報:")
stats = db.get_stats()
print(f" データベース名: {stats['db_name']}")
for collection_name, collection_stats in stats['collections'].items():
print(f" {collection_name}: {collection_stats['count']} 件")
if collection_stats['indexes']:
print(f" インデックス: {collection_stats['indexes']}")
# 削除例
print("\n🗑️ 削除例:")
# 特定のユーザーを削除
deleted = users.delete_one({'name': 'Bob'})
print(f" Bob を削除: {deleted}")
# 残りのユーザー数
remaining_users = users.count_documents()
print(f" 残りのユーザー数: {remaining_users}")
print("\n🎉 すべての操作が完了しました!")
print("=" * 50)
# クリーンアップ
print("🧹 クリーンアップ中...")
db.drop_database()
print("✅ データベースを削除しました")
if __name__ == '__main__':
main()