Sub topic 5
Adding rules with the EntityRuler
This chapter assumes you can run a pretrained spaCy pipeline and read doc.ents, as covered in the previous chapter. It also assumes you know what a Token and a Span are.
A statistical NER model predicts entities from patterns it learned in training data. That works well for common names and poorly for things the model never saw, such as your product names, internal ticket formats, or a fixed list of company names. The EntityRuler is a pipeline component that labels spans with rules. You can use it alone, or put it next to a statistical model and decide which one wins when they disagree.
What the EntityRuler does
The EntityRuler takes a list of patterns. Each pattern has a label and a pattern. When the pipeline runs, the ruler finds every match in the Doc and writes the matches to doc.ents.
It supports two kinds of pattern:
| Pattern kind | Written as | Matched by | Best for |
|---|---|---|---|
| Phrase pattern | a string, such as `"Kiro"` | `PhraseMatcher` | Fixed names and gazetteers (lists of known names) |
| Token pattern | a list of dicts, such as `[{"LOWER": "spacy"}]` | `Matcher` | Names with variable parts, such as a number or a case variation |
A phrase pattern is tokenized with the pipeline's tokenizer, then matched token by token. This means the pattern and the text are split the same way, which avoids most whitespace and punctuation mismatches.
Where the ruler sits in the pipeline
Component order decides what happens when a rule and the model both claim the same text.
- Ruler before
ner: the ruler sets entities first. The statistical component treats them as fixed and predicts entities only around them. Your rules win, and the model can still use them as context. - Ruler after
ner: the model predicts first. By default the ruler adds only matches that do not overlap an existing entity. If you setoverwrite_entstoTrue, the ruler replaces overlapping model entities.
Putting the ruler before ner is the usual choice when you have trusted rules. Putting it after is useful when you want the model to lead and the rules to fill gaps.
Your first ruler
This is the example from the chapter plan. It adds the ruler before the statistical component of a pretrained pipeline.
import spacy
nlp = spacy.load("en_core_web_sm")
ruler = nlp.add_pipe("entity_ruler", before="ner")
ruler.add_patterns([
{"label": "ORG", "pattern": "Kiro"},
{"label": "PRODUCT", "pattern": [{"LOWER": "spacy"}, {"LOWER": "pipeline"}]},
])
doc = nlp("Kiro published a new spaCy pipeline guide.")
print([(ent.text, ent.label_) for ent in doc.ents])"Kiro" is a phrase pattern and matches that exact text. The second pattern is a token pattern. It matches two consecutive tokens whose lowercase forms are spacy and pipeline, so spaCy pipeline matches whatever its capitalization. The ruler's entities appear in the output regardless of what the model thinks. Other entities in the sentence come from the model.
add_pipe returns the component, which is why ruler.add_patterns works on the next line. To confirm the order, print nlp.pipe_names. The name entity_ruler should come before ner.
Testing rules without a model
A blank pipeline is the fastest way to test patterns, because only your rules can produce entities. Anything that appears or fails to appear is caused by the patterns.
import spacy
nlp = spacy.blank("en")
ruler = nlp.add_pipe("entity_ruler")
ruler.add_patterns([
{
"label": "LANG_VERSION",
"pattern": [
{"LOWER": "python"},
{"TEXT": {"REGEX": r"^\d+(\.\d+)*$"}},
],
},
])
doc = nlp("We upgraded from Python 3.9 to python 3.12 last week.")
print([(ent.text, ent.label_) for ent in doc.ents])[('Python 3.9', 'LANG_VERSION'), ('python 3.12', 'LANG_VERSION')]The first token matches case-insensitively through LOWER. The second token must match a regular expression: digits, optionally followed by dot-separated digit groups. The regex runs on a single token, never across tokens. A pattern that expects a multi-token string in one regex will not match.
Case-insensitive phrase patterns
Phrase patterns compare the token's ORTH (exact text) by default. To match without regard to case, set phrase_matcher_attr when you create the component.
import spacy
nlp = spacy.blank("en")
ruler = nlp.add_pipe("entity_ruler", config={"phrase_matcher_attr": "LOWER"})
ruler.add_patterns([{"label": "PRODUCT", "pattern": "Kiro CLI"}])
doc = nlp("Install kiro cli today.")
print([(ent.text, ent.label_) for ent in doc.ents])[('kiro cli', 'PRODUCT')]This setting applies to every phrase pattern in that ruler. If you need case-insensitivity for only some names, write those as token patterns with LOWER, or use two rulers.
Entity IDs and overlapping matches
Several surface forms often name the same thing. A pattern can carry an id, which spaCy stores in ent.ent_id_. You can then group variants under one canonical identifier.
import spacy
nlp = spacy.blank("en")
ruler = nlp.add_pipe("entity_ruler")
ruler.add_patterns([
{"label": "PRODUCT", "pattern": "Kiro CLI", "id": "kiro"},
{"label": "PRODUCT", "pattern": "Kiro", "id": "kiro"},
])
doc = nlp("Kiro CLI and Kiro")
print([(ent.text, ent.label_, ent.ent_id_) for ent in doc.ents])[('Kiro CLI', 'PRODUCT', 'kiro'), ('Kiro', 'PRODUCT', 'kiro')]This example also shows overlap handling. At the start of the text, both Kiro and Kiro CLI match. The ruler keeps the longer match, so you do not need to order patterns so that longer ones come first. An entity cannot overlap another entity in doc.ents, so the ruler resolves every conflict before it writes the result.
Changing the model-versus-rules policy
If you want rules to correct a model that is already running, place the ruler after ner and allow it to overwrite.
import spacy
nlp = spacy.load("en_core_web_sm")
ruler = nlp.add_pipe(
"entity_ruler",
after="ner",
config={"overwrite_ents": True},
)
ruler.add_patterns([{"label": "ORG", "pattern": "Apple Park"}])Compare this with the ruler-before-ner setup. Here the model has already produced its output, and the ruler only patches it. A model entity that overlaps a rule match is removed. This is simple, but the model never sees your rule results, so it cannot use them as context for its other predictions.
Saving and sharing patterns
Keep patterns in a JSONL file (one JSON object per line) so that they can be reviewed and versioned without changing code.
import spacy
nlp = spacy.blank("en")
ruler = nlp.add_pipe("entity_ruler")
ruler.add_patterns([{"label": "ORG", "pattern": "Kiro"}])
ruler.to_disk("patterns.jsonl")
nlp2 = spacy.blank("en")
ruler2 = nlp2.add_pipe("entity_ruler")
ruler2.from_disk("patterns.jsonl")
print([(e.text, e.label_) for e in nlp2("Kiro is here.").ents])When you save the whole pipeline with nlp.to_disk, the ruler's patterns are saved with it. Loading the pipeline restores them.
Common errors
- The rule never fires. Check
nlp.pipe_namesfirst. Then check the case: a phrase pattern"kiro"does not matchKirounlessphrase_matcher_attris"LOWER". Then check tokenization: print[t.text for t in nlp.make_doc(text)]and confirm that the tokens match what your token pattern expects. - The model entity wins. The ruler is after
nerandoverwrite_entsisFalse. Move it beforeneror enable overwriting. - A regex matches nothing. Token-pattern regexes are applied to one token.
"Python 3.12"is two tokens, so one regex for the whole string fails. - An invalid pattern fails or is ignored. Set
"validate": Truein the component config while developing. spaCy then reports misspelled attribute names and malformed operators when you add the patterns. Turn it off in production if loading speed matters. - Different tools give different results. Rules depend on the tokenizer. A pipeline with different tokenizer exceptions can split the same text differently, so retest patterns when you change pipelines.
What rules cannot do
Rules do not generalize. A list of company names will not find a company that is missing from the list, and a rule for Python 3.x will not cope with a new phrasing. Rules also cannot tell apart names that are spelled the same but used differently, such as Apple the company and apple the fruit, unless you add context to the pattern. Use rules for closed lists and strict formats. Use a statistical or transformer model for open-ended categories. A combined pipeline often works best: rules for the names you know and a model for the rest. The last chapter compares these options in more detail.
Exercise
You load encorewebsm and add an entityruler after ner with default settings. You add the pattern {"label": "ORG", "pattern": "Mercury"}. The model already labels "Mercury" as LOC in "Mercury is closest to the Sun." Which label does the final entity have, and what two changes would make the rule win?
Show answer
The final label stays LOC. With the default overwriteents=False, the ruler adds only matches that do not overlap an existing entity, and Mercury already overlaps one. To make the rule win, either add the ruler before ner (nlp.addpipe("entityruler", before="ner")), or keep it after ner and set config={"overwriteents": True}.
Exercise
Write a token pattern for a ticket identifier of the form "TKT" followed by a number, written as two tokens, such as "TKT 4821". It should match "tkt" in any case and use the label TICKET. Why can't a single regex on one token match "TKT 4821"?
Show answer
Pattern: {"label": "TICKET", "pattern": [{"LOWER": "tkt"}, {"IS_DIGIT": True}]}. A token-pattern regex such as {"TEXT": {"REGEX": ...}} is tested against one token at a time. "TKT 4821" is two tokens, so no single token contains the whole string.