• Stars
    star
    127
  • Rank 282,790 (Top 6 %)
  • Language
    Python
  • License
    Apache License 2.0
  • Created over 3 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Check for multiple patterns in a single string at the same time: a fast Aho-Corasick algorithm for Python

ahocorasick_rs: Quickly search for multiple substrings at once

ahocorasick_rs allows you to search for multiple substrings ("patterns") in a given string ("haystack") using variations of the Aho-Corasick algorithm.

In particular, it's implemented as a wrapper of the Rust aho-corasick library, and provides a faster alternative to the pyahocorasick library.

Found any problems or have any questions? File an issue on the GitHub project.

Quickstart

The ahocorasick_rs library allows you to search for multiple strings ("patterns") within a haystack. For example, let's install the library:

$ pip install ahocorasick-rs

Then, we can construct a AhoCorasick object:

>>> import ahocorasick_rs
>>> patterns = ["hello", "world", "fish"]
>>> haystack = "this is my first hello world. hello!"
>>> ac = ahocorasick_rs.AhoCorasick(patterns)

You can construct a AhoCorasick object from any iterable (including generators), not just lists:

>>> ac = ahocorasick_rs.AhoCorasick((p.lower() for p in patterns))

AhoCorasick.find_matches_as_indexes() returns a list of tuples, each tuple being:

  1. The index of the found pattern inside the list of patterns.
  2. The start index of the pattern inside the haystack.
  3. The end index of the pattern inside the haystack.
>>> ac.find_matches_as_indexes(haystack)
[(0, 17, 22), (1, 23, 28), (0, 30, 35)]
>>> patterns[0], patterns[1], patterns[0]
('hello', 'world', 'hello')
>>> haystack[17:22], haystack[23:28], haystack[30:35]
('hello', 'world', 'hello')

find_matches_as_strings() returns a list of found patterns:

>>> ac.find_matches_as_strings(haystack)
['hello', 'world', 'hello']

Choosing the matching algorithm

Match kind

There are three ways you can configure matching in cases where multiple patterns overlap. For a more in-depth explanation, see the underlying Rust library's documentation of matching.

Assume we have this starting point:

>>> from ahocorasick_rs import AhoCorasick, MatchKind

Standard (the default)

This returns the pattern that matches first, semantically-speaking. This is the default matching pattern.

>>> ac AhoCorasick(["disco", "disc", "discontent"])
>>> ac.find_matches_as_strings("discontent")
['disc']
>>> ac = AhoCorasick(["b", "abcd"])
>>> ac.find_matches_as_strings("abcdef")
['b']

In this case disc will match before disco or discontent.

Similarly, b will match before abcd because it ends earlier in the haystack than abcd does:

>>> ac = AhoCorasick(["b", "abcd"])
>>> ac.find_matches_as_strings("abcdef")
['b']

LeftmostFirst

This returns the leftmost-in-the-haystack matching pattern that appears first in the list of given patterns. That means the order of patterns makes a difference:

>>> ac = AhoCorasick(["disco", "disc"], matchkind=MatchKind.LeftmostFirst)
>>> ac.find_matches_as_strings("discontent")
['disco']
>>> ac = AhoCorasick(["disc", "disco"], matchkind=MatchKind.LeftmostFirst)
['disc']

Here we see abcd matched first, because it starts before b:

>>> ac = AhoCorasick(["b", "abcd"], matchkind=MatchKind.LeftmostFirst)
>>> ac.find_matches_as_strings("abcdef")
['abcd']
LeftmostLongest

This returns the leftmost-in-the-haystack matching pattern that is longest:

>>> ac = AhoCorasick(["disco", "disc", "discontent"], matchkind=MatchKind.LeftmostLongest)
>>> ac.find_matches_as_strings("discontent")
['discontent']

Overlapping matches

You can get all overlapping matches, instead of just one of them, but only if you stick to the default matchkind, MatchKind.Standard:

>>> from ahocorasick_rs import AhoCorasick
>>> patterns = ["winter", "onte", "disco", "discontent"]
>>> ac = AhoCorasick(patterns)
>>> ac.find_matches_as_strings("discontent", overlapping=True)
['disco', 'onte', 'discontent']

Additional configuration: speed and memory usage tradeoffs

Algorithm implementations: trading construction speed, memory, and performance

You can choose the type of underlying automaton to use, with different performance tradeoffs. The short version: if you want maximum matching speed, and you don't have too many patterns, try the Implementation.DFA implementation and see if it helps.

The underlying Rust library supports four choices, which are exposed as follows:

  • None uses a heuristic to choose the "best" Aho-Corasick implementation for the given patterns, balancing construction time, memory usage, and matching speed. This is the default.
  • Implementation.NoncontiguousNFA: A noncontiguous NFA is the fastest to be built, has moderate memory usage and is typically the slowest to execute a search.
  • Implementation.ContiguousNFA: A contiguous NFA is a little slower to build than a noncontiguous NFA, has excellent memory usage and is typically a little slower than a DFA for a search.
  • Implementation.DFA: A DFA is very slow to build, uses exorbitant amounts of memory, but will typically execute searches the fastest.
>>> from ahocorasick_rs import AhoCorasick, Implementation
>>> ac = AhoCorasick(["disco", "disc"], implementation=Implementation.DFA)

Trading memory for speed

If you use find_matches_as_strings(), there are two ways strings can be constructed: from the haystack, or by caching the patterns on the object. The former takes more work, the latter uses more memory if the patterns would otherwise have been garbage-collected. You can control the behavior by using the store_patterns keyword argument to AhoCorasick().

  • AhoCorasick(..., store_patterns=None): The default. Use a heuristic (currently, whether the total of pattern string lengths is less than 4096 characters) to decide whether to store patterns or not.
  • AhoCorasick(..., store_patterns=True): Keep references to the patterns, potentially speeding up find_matches_as_strings() at the cost of using more memory. If this uses large amounts of memory this might actually slow things down due to pressure on the CPU memory cache, and/or the performance benefit might be overwhelmed by the algorithm's search time.
  • AhoCorasick(..., store_patterns=False): Don't keep references to the patterns, saving some memory but potentially slowing down find_matches_as_strings(), especially when there are only a small number of patterns and you are searching a small haystack.

Implementation details

  • Matching releases the GIL, to enable concurrency.
  • Not all features from the underlying library are exposed; if you would like additional features, please file an issue or submit a PR.

Benchmarks

As with any benchmark, real-world results will differ based on your particular situation. If performance is important to your application, measure the alternatives yourself!

That being said, I've seen ahocorasick_rs run 1.5Γ— to 7Γ— as fast as pyahocorasick, depending on the options used. You can run the included benchmarks, if you want, to see some comparative results locally. Clone the repository, then:

pip install pytest-benchmark ahocorasick_rs pyahocorasick
pytest benchmarks/

More Repositories

1

consuldotnet

Consul.NET is a .NET client library for the Consul HTTP API
C#
316
star
2

armada

A multi-cluster batch queuing system for high-throughput workloads on Kubernetes.
Go
201
star
3

siembol

An open-source, real-time Security Information & Event Management tool based on big data technologies, providing a scalable, advanced security analytics framework.
Java
188
star
4

ParquetSharp

ParquetSharp is a .NET library for reading and writing Apache Parquet files.
C#
140
star
5

spark-extension

A library that provides useful extensions to Apache Spark and PySpark.
Scala
138
star
6

fasttrackml

Experiment tracking server focused on speed and scalability
Go
97
star
7

grpc_async_examples

C++
49
star
8

TypeEquality

Type equality for F#
F#
43
star
9

spark-dgraph-connector

A connector for Apache Spark and PySpark to Dgraph databases.
Scala
40
star
10

geras

Geras provides a Thanos Store API for the OpenTSDB HTTP API. This makes it possible to query OpenTSDB via PromQL, through Thanos.
Go
38
star
11

prommsd

Go
30
star
12

thanos-remote-read

Adapter to query Thanos StoreAPI with Prometheus remote read support.
Go
30
star
13

fsharp-formatting-conventions

G-Research F# code formatting guidelines
18
star
14

ParquetSharp.DataFrame

ParquetSharp.DataFrame is a .NET library for reading and writing Apache Parquet files into/from .NET DataFrames, using ParquetSharp
C#
18
star
15

Peregrine

F#
14
star
16

Tack

A DotNet tool that can be used to get filter projects and associated output assemblies from solutions
C#
12
star
17

ProjectLinter

An MSBuild project file linter to validate project file as part of build process
C#
12
star
18

DotNetDockerTest

C#
12
star
19

SolutionValidator

A tool for validating solution files and viewing project dependencies
C#
12
star
20

Bulldog

An opinionated base library for building dotnet tools
C#
12
star
21

VsTestRunner

A DotNet tool which can be used to run dotnet vstest across a set of assemblies
C#
12
star
22

fast-string-search

Python
12
star
23

NuGetPackageChecker

An MSBuild extension to check for required packages and versions
C#
12
star
24

ApiSurface

F#
11
star
25

HiddenWindow

C#
10
star
26

dgraph-dbpedia

Pre-processing DBpedia datasets to load into Dgraph
Scala
10
star
27

fsharp-analyzers

Analyzers for F#
F#
8
star
28

yunikorn-history-server

A service to store and provide historical data for K8S clusters using the Yunikorn scheduler
Go
8
star
29

charts

Repository for all of G Research-hosted helm charts
Mustache
7
star
30

opentsdb-tsuid-ratelimiter

Java
7
star
31

DotNetPerfMonitor

Monitoring performance of the .NET ecosystem (NuGet, MsBuild, C#, F#)
PowerShell
6
star
32

dgraph-lanl-csr

Project to load the "Comprehensive, Multi-Source Cyber-Security Events" dataset into a Dgraph cluster.
Scala
6
star
33

NuPerfMonitor

Monitoring performance of NuGet package manager
PowerShell
5
star
34

fasttrackml-ui-aim

Modern Aim UI built for FastTrackML
Go
5
star
35

prometheus-config-loader

Go
4
star
36

PalletJack

Parquet extension
Python
4
star
37

brand

G-Research branding assets
4
star
38

System.Net.Http.JsonExtensions

C#
2
star
39

armada-jupyter

Python
2
star
40

go-ntlm-auth

Go
2
star
41

siembol-config

A Siembol configuration repository for a Siembol quickstart demo
2
star
42

tfe-plan-bot

Terraform Enterprise/Cloud Plan Bot
Go
1
star
43

fasttrackml-ui-mlflow

Classic MLFlow UI built for FastTrackML
Go
1
star
44

astral

Ruby
1
star
45

bearcat

Python
1
star