Skip to content

Commit 662e5c0

Browse files
Move some search related utilities to search_tester to make them usable
1 parent 7a13d97 commit 662e5c0

2 files changed

Lines changed: 49 additions & 63 deletions

File tree

docker/mongodb-kubernetes-tests/tests/common/search/search_tester.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
from typing import Optional, Self
22

3+
import pymongo
4+
import pymongo.errors
5+
36
import kubetester
47
from kubetester.mongotester import MongoTester
58
from pymongo.operations import SearchIndexModel
@@ -74,6 +77,34 @@ def for_sharded(
7477
)
7578
return cls(conn_str, use_ssl=use_ssl, ca_path=ca_path)
7679

80+
def enable_sharding(self, database_name: str):
81+
try:
82+
self.client.admin.command("enableSharding", database_name)
83+
logger.info(f"Sharding enabled on {database_name} database")
84+
except pymongo.errors.OperationFailure as e:
85+
if (
86+
"already enabled" in str(e) or e.code == 23 or e.code == 59
87+
): # AlreadyInitialized or CommandNotFound (MongoDB 8.0+)
88+
logger.info(f"Sharding already enabled on {database_name}")
89+
else:
90+
raise
91+
92+
def shard_collection(self, database_name: str, collection_name: str):
93+
ns = f"{database_name}.{collection_name}"
94+
try:
95+
self.client[database_name][collection_name].create_index([("_id", pymongo.HASHED)])
96+
self.client.admin.command("shardCollection", ns, key={"_id": "hashed"})
97+
logger.info(f"{collection_name} collection sharded")
98+
except pymongo.errors.OperationFailure as e:
99+
if "already sharded" in str(e) or e.code == 20: # AlreadyInitialized for sharding
100+
logger.info(f"{collection_name} collection already sharded")
101+
else:
102+
raise
103+
104+
def search(self, database_name: str, collection_name: str, pipeline: list):
105+
"""Run a search aggregation pipeline and return the results."""
106+
return list(self.client[database_name][collection_name].aggregate(pipeline))
107+
77108
def mongorestore_from_url(self, archive_url: str, ns_include: str, tools_pod: ToolsPod):
78109
"""Run mongorestore from a URL using the tools pod.
79110

docker/mongodb-kubernetes-tests/tests/search/search_sharded_external_mongod_single_mongot.py

Lines changed: 18 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -495,44 +495,9 @@ def test_search_restore_sample_database(mdb: MongoDB, tools_pod: mongodb_tools_p
495495
@mark.e2e_search_sharded_external_mongod_single_mongot
496496
def test_search_shard_collections(mdb: MongoDB):
497497
search_tester = get_admin_search_tester(mdb, use_ssl=True)
498-
client = search_tester.client
499-
admin_db = client.admin
500-
sample_mflix_db = client["sample_mflix"]
501-
502-
# Enable sharding on database
503-
try:
504-
admin_db.command("enableSharding", "sample_mflix")
505-
logger.info("Sharding enabled on sample_mflix database")
506-
except pymongo.errors.OperationFailure as e:
507-
if (
508-
"already enabled" in str(e) or e.code == 23 or e.code == 59
509-
): # AlreadyInitialized or CommandNotFound (MongoDB 8.0+)
510-
logger.info("Sharding already enabled on sample_mflix")
511-
else:
512-
raise
513-
514-
# Shard movies collection
515-
try:
516-
sample_mflix_db["movies"].create_index([("_id", pymongo.HASHED)])
517-
admin_db.command("shardCollection", "sample_mflix.movies", key={"_id": "hashed"})
518-
logger.info("movies collection sharded")
519-
except pymongo.errors.OperationFailure as e:
520-
if "already sharded" in str(e) or e.code == 20: # AlreadyInitialized for sharding
521-
logger.info("movies collection already sharded")
522-
else:
523-
raise
524-
525-
# Shard embedded_movies collection
526-
try:
527-
sample_mflix_db["embedded_movies"].create_index([("_id", pymongo.HASHED)])
528-
admin_db.command("shardCollection", "sample_mflix.embedded_movies", key={"_id": "hashed"})
529-
logger.info("embedded_movies collection sharded")
530-
except pymongo.errors.OperationFailure as e:
531-
if "already sharded" in str(e) or e.code == 20: # AlreadyInitialized for sharding
532-
logger.info("embedded_movies collection already sharded")
533-
else:
534-
raise
535-
498+
search_tester.enable_sharding("sample_mflix")
499+
search_tester.shard_collection("sample_mflix", "movies")
500+
search_tester.shard_collection("sample_mflix", "embedded_movies")
536501
# Wait for balancer to distribute chunks
537502
# TODO: execute mdb command to wait for the balancer
538503
time.sleep(10)
@@ -559,15 +524,11 @@ def test_search_assert_search_query(mdb: MongoDB):
559524

560525
def execute_search():
561526
try:
562-
results = list(
563-
search_tester.client["sample_mflix"]["movies"].aggregate(
564-
[
565-
{"$search": {"index": "default", "text": {"query": "star wars", "path": "title"}}},
566-
{"$limit": 10},
567-
{"$project": {"_id": 0, "title": 1, "score": {"$meta": "searchScore"}}},
568-
]
569-
)
570-
)
527+
results = search_tester.search("sample_mflix", "movies", [
528+
{"$search": {"index": "default", "text": {"query": "star wars", "path": "title"}}},
529+
{"$limit": 10},
530+
{"$project": {"_id": 0, "title": 1, "score": {"$meta": "searchScore"}}},
531+
])
571532

572533
result_count = len(results)
573534
logger.info(f"Search returned {result_count} results")
@@ -587,26 +548,20 @@ def execute_search():
587548
@mark.e2e_search_sharded_external_mongod_single_mongot
588549
def test_search_verify_results_from_all_shards(mdb: MongoDB):
589550
search_tester = get_user_search_tester(mdb, use_ssl=True)
590-
movies_collection = search_tester.client["sample_mflix"]["movies"]
591-
592551
# Get total document count
593-
total_docs = movies_collection.count_documents({})
552+
total_docs = search_tester.client["sample_mflix"]["movies"].count_documents({})
594553
logger.info(f"Total documents in collection: {total_docs}")
595554

596555
# Execute wildcard search to get all documents
597-
results = list(
598-
movies_collection.aggregate(
599-
[
600-
{
601-
"$search": {
602-
"index": "default",
603-
"wildcard": {"query": "*", "path": "title", "allowAnalyzedField": True},
604-
}
605-
},
606-
{"$project": {"_id": 0, "title": 1}},
607-
]
608-
)
609-
)
556+
results = search_tester.search("sample_mflix", "movies", [
557+
{
558+
"$search": {
559+
"index": "default",
560+
"wildcard": {"query": "*", "path": "title", "allowAnalyzedField": True},
561+
}
562+
},
563+
{"$project": {"_id": 0, "title": 1}},
564+
])
610565

611566
search_count = len(results)
612567
logger.info(f"Search through mongos returned {search_count} documents")

0 commit comments

Comments
 (0)