An open source, non-profit web search engine
Parse URLs faster using a regex
Daoud Clarke9201c76bbc8f
diff --git a/mwmbl/count_urls.py b/mwmbl/count_urls.pyindex d208d62..5a8feff 100644--- a/mwmbl/count_urls.py+++ b/mwmbl/count_urls.py@@ -4,13 +4,12 @@ from datetime import date, timedelta, datetimefrom logging import getLoggerfrom pathlib import Pathfrom time import sleep-from urllib.parse import urlparsefrom django.conf import settingsfrom redis import Redisfrom mwmbl.tinysearchengine.indexer import TinyIndex, Document-from mwmbl.utils import batch+from mwmbl.utils import batch, parse_urlINDEX_RESULT_COUNT_KEY = "index-result-count-{date}"INDEX_DOMAIN_COUNT_KEY = "index-domain-count-{date}"@@ -53,6 +52,7 @@ def count_urls():domain_hll_key = INDEX_DOMAIN_HLL_KEY.format(date=today)domain_count_key = INDEX_DOMAIN_RESULT_COUNT_KEY.format(date=today)num_results = 0+ start_time = datetime.utcnow()with TinyIndex(item_factory=Document, index_path=index_path) as tiny_index:# Count using a Redis hyperloglog to avoid memory issues.for page_indexes in batch(range(tiny_index.num_pages), NUM_PAGES_IN_BATCH):@@ -62,7 +62,7 @@ def count_urls():for i in page_indexes:docs = tiny_index.get_page(i)urls |= {doc.url for doc in docs}- page_domains = [urlparse(doc.url).netloc for doc in docs]+ page_domains = [parse_url(doc.url).netloc for doc in docs]domain_counts.update(page_domains)domains |= set(page_domains)num_results += len(docs)@@ -88,6 +88,9 @@ def count_urls():_set_count(INDEX_DOMAIN_COUNT_KEY, redis, today, domain_count)_set_count(INDEX_RESULT_COUNT_KEY, redis, today, num_results)+ end_time = datetime.utcnow()+ logger.info(f"Counting took {end_time - start_time}.")+def _set_count(key, redis, today, count):redis.set(key.format(date=today), count)diff --git a/mwmbl/utils.py b/mwmbl/utils.pyindex 97be262..26c4cb4 100644--- a/mwmbl/utils.py+++ b/mwmbl/utils.py@@ -1,4 +1,5 @@import re+from dataclasses import dataclassfrom typing import Sequencefrom mwmbl.indexer.index import tokenize_document@@ -41,3 +42,25 @@ def add_term_infos(documents: list[Document], index: TinyIndex, page_index: int)yield add_term_info(document, index, page_index)except ValueError:continue+++@dataclass+class ParsedUrl:+ scheme: str+ netloc: str+ query_string: str+ fragment: str+++# See https://stackoverflow.com/a/2627127/660902+URL_REGEX = re.compile("^(([^:/?#]+):)?(//([^/?#]*)|///)?([^?#]*)(\\?[^#]*)?(#.*)?")+++def parse_url(url: str) -> ParsedUrl:+ """+ Custom URL parsing function using regex because urlparse is too slow.+ """+ results = URL_REGEX.match(url)+ if results is None:+ raise ValueError(f"Unable to parse URL {url}")+ return ParsedUrl(results.group(2), results.group(4), results.group(6), results.group(7))diff --git a/test/test_utils.py b/test/test_utils.pynew file mode 100644index 0000000..54f663a--- /dev/null+++ b/test/test_utils.py@@ -0,0 +1,10 @@+from mwmbl.utils import parse_url+++def test_parse_url():+ url = "https://www.google.com/search?q=python+parse+url+regex#result"+ parsed = parse_url(url)+ assert parsed.scheme == "https"+ assert parsed.netloc == "www.google.com"+ assert parsed.query_string == "?q=python+parse+url+regex"+ assert parsed.fragment == "#result"