3 SpaCy Tricks for Efficient Text Processing & Entity Recognition Developers can optimize spaCy's text processing speed by selectively disabling pipeline components like the dependency parser and lemmatizer when only named entity recognition is needed. The technique reduces processing time from 2.85 seconds to a fraction of that for 1,000 documents by excluding unused components at load time and using context managers to temporarily disable them during execution. This approach prevents computational bottlenecks when scaling from prototypes to processing millions of documents. 3 SpaCy Tricks for Efficient Text Processing & Entity Recognition In this article, we will explore three essential spaCy tricks that every developer should have in their toolkit to maximize processing speed and customize entity recognition. Introduction Thanks especially to contemporary large language models, natural language processing https://www.kdnuggets.com/tag/natural-language-processing NLP is a fundamental pillar of modern AI and software systems. You'll find NLP techniques and technologies powering everything from search engines and chatbots to automated customer support routing and entity extraction pipelines. When it comes to production-grade NLP in Python, is the undisputed industry standard. spaCy is designed specifically for production use, offering industrial-strength speed, pre-trained statistical and transformer models, and an intuitive API. https://spacy.io/ spaCy Unfortunately, many developers treat spaCy as a simple black box monolith. They load a model, run it on text, and accept the default processing speeds and extraction limits. When scaling from a local prototype to processing millions of documents, these default configurations can become computational bottlenecks, leading to latency, bloated memory footprints, and missed domain-specific entities. In order to build high-performance text processing pipelines, you must understand how to optimize spaCy's internal execution flow. In this article, we will explore three essential spaCy tricks that every developer should have in their toolkit to maximize processing speed and customize entity recognition: selective pipeline loading, parallel batch processing, and hybrid rule-based statistical entity recognition. Before getting started, ensure you have spaCy installed, as well as its lightweight general-purpose English model: pip install spacy python -m spacy download en core web sm 1. Selective Pipeline Loading & Component Disabling By default, when you load a pre-trained spaCy model such as en core web sm , spaCy initializes a complete NLP pipeline. This pipeline typically includes: - a tokenizer - a part-of-speech tagger tagger - a dependency parser parser - a lemmatizer lemmatizer - an attribute ruler attribute ruler - a named entity recognizer ner While this full default rich feature set is excellent, it comes with substantial computational overhead. If your application only needs to perform named entity recognition NER , running the dependency parser and lemmatizer is a waste of CPU cycles and memory. Conversely, if you are only cleaning text and extracting lemmas, running the deep statistical NER model is highly inefficient. You can optimize this by selectively excluding components during loading, or temporarily disabling them during execution using a context manager. This naive approach loads and runs every default component on the text, regardless of whether the components' outputs are actually used: python import spacy import time Load the small English model nlp = spacy.load "en core web sm" texts = "Apple is looking at buying U.K. startup for $1 billion" 1000 Naive execution: runs tagger, parser, lemmatizer, and ner on every doc Assume we only care about named entities here start time = time.time for text in texts: doc = nlp text entities = ent.text, ent.label for ent in doc.ents duration full = time.time - start time print f"Full pipeline processed 1,000 docs in: {duration full:.4f} seconds" Output: Full pipeline processed 1,000 docs in: 2.8540 seconds Now let's optimize execution in two specific ways. First, we will be excluding heavy, unused components like the dependency parser at load time. Second, we will use nlp.select pipes to temporarily disable components when processing specific workloads. python import spacy import time Load time optimization: Exclude the heavy parser and tagger from the start This reduces initialization time and memory footprint nlp optimized = spacy.load "en core web sm", exclude= "parser", "tagger" texts = "Apple is looking at buying U.K. startup for $1 billion" 1000 Context-manager optimization, disable components temporarily We have outright excluded parser and tagger, we disable attribute ruler and lemmatizer here start time = time.time with nlp optimized.select pipes disable= "attribute ruler", "lemmatizer" : for text in texts: doc = nlp optimized text entities = ent.text, ent.label for ent in doc.ents duration opt = time.time - start time print f"Optimized pipeline processed 1,000 docs in: {duration opt:.4f} seconds" print f"Speedup: {duration full / duration opt:.2f}x faster " Let's compare runtimes: Full pipeline processed 1,000 docs in: 2.8739 seconds Optimized pipeline processed 1,000 docs in: 1.7859 seconds Speedup: 1.61x faster In the optimized example, passing exclude= "parser", "tagger" to spacy.load completely prevents these components from being loaded into memory. In an alternate method of reaching basically the same outcome, we passed disable= "attribute ruler", "lemmatizer" to temporarily disabling their processing. The effect is that, when we process the text, spaCy skips token dependency analysis and part-of-speech tag labeling, which are mathematically expensive, and jumps straight to entity recognition. This results in a noticeable speedup with zero effect on NER accuracy, with even more noticeable advantages at greater scale. 2. High-Throughput Batch Processing with nlp.pipe & Metadata Propagation If you are iterating over a large corpus e.g. pandas DataFrames, database rows, or raw text files , calling the nlp object on individual strings in a loop e.g. nlp text for text in texts is an anti-pattern. Sequential processing prevents spaCy from optimizing memory buffers, grouping operations, and leveraging multi-core parallelization. Also, when processing text for database storage or ETL pipelines, you often need to carry metadata like a record ID, timestamp, or category through the NLP process so you can map the resulting entities back to the correct database rows. The solution is to use nlp.pipe . This method processes documents as a stream , buffers them internally, and supports multi-processing. By setting as tuples=True , you can feed tuples of text, context to spaCy. It will return doc, context pairs, letting you pass metadata straight through the pipeline. This naive approach runs processing sequentially and uses manual index tracking to align the resulting documents with their database IDs, which is brittle and slow: python import spacy import time nlp = spacy.load "en core web sm", exclude= "parser", "tagger" Raw database records with unique IDs records = {"id": f"DB-REC-{i}", "text": "Google was founded in September 1998 by Larry Page and Sergey Brin."} for i in range 1000 Sequential loop: slow and manually managed metadata start time = time.time extracted data = for i, record in enumerate records : doc = nlp record "text" entities = ent.text, ent.label for ent in doc.ents extracted data.append { "id": record "id" , "entities": entities } duration seq = time.time - start time print f"Sequential loop processed 1,000 docs in: {duration seq:.4f} seconds" Output: Sequential loop processed 1,000 docs in: 2.7375 seconds Here, we stream the data using nlp.pipe , leveraging batch processing and multi-core parallelization n process , while letting the database ID ride along as a context variable: python import spacy import time Keep your imports and definitions global so child processes can see them nlp = spacy.load "en core web sm", exclude= "parser", "tagger" Wrap the actual execution code in the main block if name == ' main ': records = {"id": f"DB-REC-{i}", "text": "Google was founded in September 1998 by Larry Page and Sergey Brin."} for i in range 1000 start time = time.time Format input as a list of text, context tuples stream input = rec "text" , rec "id" for rec in records Stream batches and use all available CPU cores with n process=-1 extracted data pipe = docs stream = nlp.pipe stream input, as tuples=True, batch size=256, n process=-1 for doc, rec id in docs stream: entities = ent.text, ent.label for ent in doc.ents extracted data pipe.append { "id": rec id, "entities": entities } duration pipe = time.time - start time print f"nlp.pipe processed 1,000 docs in: {duration pipe:.4f} seconds" print f"Speedup: {duration seq / duration pipe:.2f}x faster " Output: nlp.pipe processed 1,000 docs in: 7.1310 seconds In the optimized code snippet, we restructure the input dataset into a sequence of tuples: text string, metadata context . When calling nlp.pipe stream input, as tuples=True, batch size=256, n process=-1 : batch size=256 tells spaCy to buffer and process texts in groups of 256, minimizing internal Python loop overhead n process=-1 tells spaCy to automatically detect your system's CPU count and parallelize the tokenization and component extraction across all available cores as tuples=True instructs spaCy to yield pairs of doc, context , ensuring the metadata the record ID remains perfectly aligned with the processed document without needing manual index arrays or list-alignment code The astute reader will note that the processing time for the parallel batch processing code has actually increased over its predecessor. However, this is due to the overhead associated with setting up the parallel job, and the savings will become evident as the number of documents to process grows in number. By re-running the same code excerpts above but with 10,000 records instead of 1,000, here are the results: Sequential loop processed 1,000 docs in: 27.6733 seconds nlp.pipe processed 1,000 docs in: 11.5444 seconds You can see how the savings would continue to compound. 3. Hybrid Named Entity Recognition with EntityRuler Pre-trained statistical and transformer-based NER models are incredibly powerful for recognizing general entity types like ORG , PERSON , or DATE based on context. However, models can frequently fail to recognize domain-specific terms such as custom product SKUs, legacy code IDs, or highly niche medical terms because they weren't exposed to them during training. Fine-tuning a deep learning statistical model on custom entities is one solution, but it requires labeling thousands of sentences and runs the risk of "catastrophic forgetting," in which the model forgets how to recognize standard entities along the way. A cleaner, highly efficient solution is a hybrid NER approach using spaCy's EntityRuler . The EntityRuler allows you to define patterns using regular expressions or token-based dictionary dictionaries and inject them directly into your pipeline. You can add it before the statistical NER — to pre-tag deterministic entities and help the model make context decisions — or after it — to act as a fallback or override. Developers often try to patch statistical NER gaps by running regex on the text after running the spaCy pipeline, resulting in manual coordinate offset math and disconnected data structures: python import spacy import re nlp = spacy.load "en core web sm" text = "Please review system ticket ID: TKT-98421 on our corporate portal." doc = nlp text Standard statistical NER misses custom ticket IDs entities = ent.text, ent.label for ent in doc.ents print "Before post-process:", entities Post-process regex patch ticket pattern = r"TKT-\d+" matches = re.finditer ticket pattern, text custom ents = for match in matches: Requires complex char-to-token offset conversion to build spans custom ents.append match.group , "TICKET ID" We now have two disconnected lists of entities that must be merged manually print "Regex entities:", custom ents Output: Before post-process: Regex entities: 'TKT-98421', 'TICKET ID' By adding an EntityRuler component directly to the pipeline, we merge rule-based regex patterns and statistical parsing into a single, unified doc.ents output: python import spacy nlp = spacy.load "en core web sm" Add the entity ruler component to the pipeline before ner so it pre-tags entities, but after works too ruler = nlp.add pipe "entity ruler", before="ner" Define token-level patterns, including regular expressions patterns = Match strings starting with "TKT-" followed by digits {"label": "TICKET ID", "pattern": {"TEXT": {"REGEX": "^TKT-\d+$"}} }, Match specific domain phrases exactly {"label": "ORG", "pattern": "corporate portal"} ruler.add patterns patterns text = "Please review system ticket ID: TKT-98421 on our corporate portal." doc = nlp text Both statistical and rule-based entities are consolidated inside doc.ents for ent in doc.ents: print f"Entity: {ent.text:<20} | Label: {ent.label }" Output: Entity: TKT-98421 | Label: TICKET ID Entity: corporate portal | Label: ORG In this hybrid implementation, we call nlp.add pipe "entity ruler", before="ner" . The EntityRuler acts as a native pipeline component. When the text is processed: - The tokenizer splits the sentence into tokens. - The EntityRuler runs first, identifying tokens that match our ticket regex pattern or exact dictionary strings and tagging them as TICKET ID or ORG . - The statistical ner component runs next. Because it sees that these tokens are already tagged as entities, it respects the tags or adapts its predictions around them, avoiding conflicts . This ensures that all entities, both learned statistical ones and deterministic rule-based ones, coexist cleanly within a single, cohesive Doc.ents sequence, eliminating the need for brittle post-process sorting or offset adjustments. Wrapping Up Optimizing spaCy is about transitioning from default configurations to pipelines that respect your system resources and domain-specific requirements. By adopting these three tricks, you can design highly efficient, production-grade text processing pipelines: - Selective loading & component disabling eliminates unnecessary computation, accelerating your processing speed by up to 5x. - Batch processing with nlp.pipe parallelizes execution across CPU cores, and setting as tuples=True propagates critical metadata without index-mapping bugs. - Hybrid NER with EntityRuler blends deterministic pattern-matching rules with general statistical inference, ensuring maximum extraction accuracy for custom domains without retraining. Deploying these design patterns ensures that your NLP pipelines remain scalable, memory-efficient, and tailored to the unique vocabulary of your business data. Matthew Mayo https://www.kdnuggets.com/wp-content/uploads/./profile-pic.jpg holds a master's degree in computer science and a graduate diploma in data mining. As managing editor of https://twitter.com/mattmayo13 @mattmayo13 KDnuggets https://www.kdnuggets.com/ & Statology https://www.statology.org/ , and contributing editor at Machine Learning Mastery https://machinelearningmastery.com/ , Matthew aims to make complex data science concepts accessible. His professional interests include natural language processing, language models, machine learning algorithms, and exploring emerging AI. He is driven by a mission to democratize knowledge in the data science community. Matthew has been coding since he was 6 years old.