Skip to content
ImagineWorld

Identity Knowledge Graphs

node_idnode-book_building-knowledge-graphs_chapter-09-identity-knowledge-graphs
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num9
chapter_titleIdentity Knowledge Graphs
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Being able to confidently identify a person or thing is a bedrock of business information systems. Given two records, can you determine if they represent the same real-world thing (a person, an organization, a place, and so on)?

This problem commonly arises when integrating data from different systems, when you need to reason that a record in one system has a counterpart (or not) in the other. In that context, it is often referred to as entity resolution or master data management.

In this chapter, you will learn how knowledge graphs help you address the problem of identity. You will see how the topology of a knowledge graph can give you the confidence to link multiple entities and allow you to reason about them as if they were a single golden record.

Identity and its myriad of difficulties is part of our everyday experience. For example, Jane Coleman has been a happy and profitable customer of the Bank’s credit card for several years.

Some months ago, Jane married her husband Peter and decided to take his name. Jane Downe and Peter Downe are the owners of a joint checking account with the Bank. But how can the Bank know that Jane Coleman and Jane Downe are the same person? There’s no obligation on Jane to tell the Bank; indeed, she is free to continue to use her maiden name (a not unusual practice among certain professionals like doctors).

As a consequence, Jane regularly gets letters in her mailbox inviting her to open a credit card account, which she already has. This is clearly a waste of time and money, and probably a modest annoyance to Jane. But were Jane to be a fraudster, then tracking down all her activities would be hampered by not being able to discern a single identity.

When records have a consistent strong identifier, then it’s easy to connect them. It’s one of the reasons why database practitioners are so concerned with things like unique identifiers to help solve that problem. At a human level, think of things like a Social Security number or a passport number for an individual, a product’s unique SKU, or a unique company identifier issued by a government agency.

But not everything is as simple as a unique identifier. There are cases like the one in the banking example described earlier where strong identifiers may exist but are not consistent across all data. Maybe Jane opened her credit card account using her driver’s license and the current account using her passport.

The data in Example 9-1 paints a typical picture of the problem. Rows 1 and 2 are easy to link. You can see they have the same Passport entry, so you can safely reason that Pete Downe and Peter J. Downe are the same person.

Example 9-1. Two records representing the same product

rowid, Source, AccountNo, Name, Passport, DriversLic, DOB
1, "Credit", 9918475, "Pete Downe", "VX83041", , 1987-03-12
2, "Current", 2436930, "Peter J. Downe", "VX83041", , 1987-03-12
3, "Credit", , "Jane Coleman", ,"49587640", 1989-10-28
4, "Current", 2436930, "Jane Downe", "RA14958", , 1989-10-28

Rows 3 and 4 in Example 9-1 are much harder to discern. There are different names (Jane’s maiden and married names) and no common alphanumeric identifiers. Given just this data, you’d have to conclude there’s a strong possibility of two people being represented in those rows.

Things become even more problematic in the absence of strong identifiers. In those cases, you will need to use whichever features are available, and often a combination, to try to determine if two similar references refer to the same thing.

There are several scenarios where you may face duplicated data. Some of the most common are:

Data integration This is probably the most frequent case. Different applications store variants of the same data for different functions, but often the data from multiple systems needs to be combined for analytics purposes. Sales applications, customer relationship management (CRM), marketing, and so on all hold customer data (or product data, or event data…), but that data is collected and managed independently. This results in records being identified and described in different ways by each, without consistent strong identifiers across systems.

Any analytic workload (analysis, reporting, predictive model building) of the integrated data is unreliable without first having solved the duplication problem. Duplicate records must be identified in order to merge them into master data entities (golden records) to establish a single trusted view.

Anonymous activity Many publicly accessible systems allow users to interact with them without authenticating (e.g., to browse products). By definition, there is no authentication of the user that can be used to identify them, but users do leave traces (clickstream) of their activity and the devices they use to access those systems. These traces will include features like time, cookie IDs, and even the navigational choices they made, which can help identify patterns and eventually unique users and sessions.

Intentional/fraudulent duplicates Sometimes duplicates are created intentionally when bad actors are trying to beat a system. Examples include:

  • Individuals trying to get better insurance quotes by slightly adjusting some parameters like their address, their age, or others
  • In more sophisticated cases, users trying to abuse service trials by authenticating with different credentials (fake emails or names, etc.)
  • Online sellers posting multiple small variants of the same product listing in an attempt to maximize its chances of being seen and ultimately sold

All these scenarios share the same fundamental question: given two records, do they refer to the same or to different entities?

Graph-Based Entity Resolution Step by Step

Section titled “Graph-Based Entity Resolution Step by Step”

The process of entity resolution includes three fundamental activities:

  • Data preparation
  • Entity matching
  • Curation of a persisted record of master entities

You can see examples of each in Example 9-2. You have three overlapping data sets with personal information that need deduplication and integration into a single view.

Example 9-2. Three sample files

file: ds1.csv

system_idfull_nameemailssnpassport_noyob
“1_1”“Sidney Bernardy”“[email protected]”“252-13-7091”“A465901”“1979”
“1_2”“Ernestine Ouchterlony”“eouchterlony1@sun.”“557-21-3938”“CF3586”“1999”
“1_3”“Cherish Gosnall”“[email protected]”“422-45-7305”“BS945813”“1983”
“1_4”“Husein Sprull”“[email protected]”“123-03-8992”“FG45867”“1980”
“1_5”“Jonathan Pedracci”“jpedraccig@gateway”“581-96-2576”null“1991”

file: ds2.csv

system_idnameemailssnpassport_noage
“2_1”“Bernardy, Sydney Jo”null“A465901”null“44”
“2_3”“Gosnall, Cherise”“[email protected]”“422-45-7305”null“40”

file: ds3.csv

system_idfirst_namelast_nameemailssnpassport_nodob
“3_1”“Syd J”“Bernardy”“[email protected]”“252-13-7091”null“1979-05-13”
“3_2”“C”“Gosnall”null“422-45-7305”null“1983-04-23”
“3_3”“Jon”“Pedracci”“[email protected]”null“TH834501”“1991-12-05”
“3_4”“Hana”“Sprull”“[email protected]”“465-63-9210”null“1984-10-13”

The purpose of the data preparation phase is to make sure that the data meets the required quality characteristics. When there are multiple data sets from independently governed systems, the different parts will also need to be harmonized to make them comparable. This will include activities like aligning data types and units (all distances in km, all prices in dollars, all scores between 0 and 1, etc.).

Even when all data comes from a single source and does not require those adjustments, all the features that you intend to use in the matching phase of the process still need to be cleansed, standardized, and so forth to maximize the quality of the results. This means making sure nulls are actually nulls (and not the string “null”), unifying string format (all uppercase or all lowercase and encoding), trimming, removing multiple spaces or special characters, and so on.

The first step is to model the data as a knowledge graph, storing it in a graph database. Since each record represents a person, the model will be the simplest possible. The obvious graph is with a Person node for each row and each column providing a property on that node. Though the files are quite similar, there are some file-specific columns (yob, age, or dob) which will introduce some variability in the node structure. This is fine for now and will be dealt with before the entity matching phase.

The Cypher script that loads each record into Person nodes is shown in Example 9-3. This generic script takes the structure (columns) in the source file and adds a property called source for data provenance.

There is never a single way of doing things in data management. Part of what was done in this phase could legitimately be carried out before the data is loaded into the graph. The data preparation work can be executed on the files directly using Python (and pandas is a great tool for this) or as SQL transformations on a cloud data warehouse after loading the files into tables. The scripts in Example 9-3 would just be loading into the graph database management system (DBMS) data in a format that is ready for entity matching (with the exception of the graph features that can only be extracted once the data is modeled as a graph). Simplicity, robustness, and performance should guide you when choosing your approach.

Example 9-3. Loading personal data files

LOAD CSV WITH HEADERS FROM "file:///ds1.csv" AS row
CREATE (p:Person) SET p.source = "ds1", p += properties(row);
LOAD CSV WITH HEADERS FROM "file:///ds2.csv" AS row
CREATE (p:Person) SET p.source = "ds2", p += properties(row);
LOAD CSV WITH HEADERS FROM "file:///ds3.csv" AS row
CREATE (p:Person) SET p.source = "ds3", p += properties(row);

The most obvious difference between the nodes generated from the different files is the level of detail in the customer’s date of birth information. While nodes from data set 1 include a year of birth (yob) property with a four-digit string representation of the year, nodes from data set 2 will have a string property called age with a representation of the current age of the customer, and nodes from data set 3 will have a dob property with a string containing the customer’s complete date of birth. To make these pieces of information comparable for the entity matching phase, the lowest common denominator in terms of information is the year of birth.

The Cypher script in Example 9-4 shows how to create a new property called m_yob (for matching year of birth) of type integer in all nodes. Notice how the source property is used to determine the type of transformation logic to be applied in each case, and number-casting functions, date functions, and arithmetic operators are used on the original data.

Example 9-4. Normalizing dates in personal data files

MATCH (p:Person) WHERE p.source = "ds1" SET p.m_yob = toInteger(p.yob);
MATCH (p:Person)
WHERE p.source = "ds2" SET p.m_yob = date().year - toInteger(p.age);
MATCH (p:Person) WHERE p.source = "ds3" SET p.m_yob = date(p.dob).year;

The name element also needs alignment, as each data set uses a different way to store names. You can see separate fields for first and last name, CSVs, and a single string containing the full name. The Cypher script in Example 9-5 creates a new property called m_fullname (for matching full name) in all nodes with type string and a “canonical” representation of a customer name: firstname lastname. The script uses the source property to apply the relevant logic implemented by using string functions (trim, toLower and tokenizer split).

Example 9-5. Normalizing names in personal data files

MATCH (p:Person)
WHERE p.source = "ds1" SET p.m_fullname = toLower(trim(p.full_name));
MATCH (p:Person) WHERE p.source = "ds2"
WITH p, split(p.name,",") AS parts
SET p.m_fullname = toLower(trim(parts[1]) + ' ' + trim(parts[0]));
MATCH (p:Person) WHERE p.source = "ds3"
SET p.m_fullname = toLower(trim(p.first_name) + ' ' + trim(p.last_name));

Once the graph data has been harmonized and normalized, it is ready for the application of the matching rules.

Optionally, the data preparation phase may include the generation of blocking keys. Blocking is a technique to reduce the search space and so improve performance. When looking for duplicates, you will need to compare every record to every other record requiring $n^2$ operations for $n$ elements.

To reduce this to a more manageable computational workload, you need to avoid comparing pairs that are not likely to produce matches. This is the job of the blocking keys.

Only candidates with the same blocking key are compared with each other. Sometimes features in the data can be used as blocking keys. For instance, you could use postal codes and then only compare records representing entities within a reasonable proximity.

Where “natural” blocking keys don’t exist, you can still generate them synthetically, including using algorithms or ML models to suggest them.

Matching is the central activity in the entity resolution process, where the identity logic is applied. You will define when two entities are considered to be the same, based on your business heuristics. This is done through the application of a set of rules based on the features identified and prepared in the preparation phase. These rules can vary in complexity but generally will be based on exact matches (useful for strong identifiers), will approximate matches based on a definition of distance (numeric, dates, embeddings), and may also introduce elements of fuzziness (string similarity, value approximation, etc.). Some rules will give unambiguous matches (e.g., a strong identifier) while others will provide weightings for probabilistic scoring.

The following algorithm provides a systematic approach to applying the matching rules:

  1. Create a SAME_AS relationship between nodes for which there is a match on a strong identifier feature.
  2. Create a weighted SIMILAR relationship between nodes for which there is a match above threshold on a weak identifier feature and a SAME_AS relationship does not exist between the two nodes.
  3. Discard the SIMILAR relationships for which there is a mismatch in one of the strong identifier features. The weight in the relationship will be the similarity score.
  4. Apply a correcting factor to the weight in a SIMILAR relationship when there is a match above threshold on a nonidentifying feature.
  5. Discard the SIMILAR relationships with a similarity score below a minimum threshold.

The application of these rules generates a graph of related nodes connected through SAME_AS and SIMILAR relationships in which connected nodes will identify unique entities. These four steps implicitly define three types of features: strong identifiers, weak identifiers, and nonidentifying features.

In Example 9-6, the two strong identifiers in the data set are the passport number (passport_no) and the Social Security number (ssn). The application of step 1 will instantiate a relationship of type SAME_AS between any pair of Person nodes that share the same value for either of the two strong identifiers.

Note the introduction of the filter on id(p1) > id(p2), avoiding the comparison of p1 versus p2 and then the superfluous p2 versus p1. This is because the SAME_AS relationship is symmetrical (if p1 is the same as p2, then p2 is the same as p1), so there is no need to compare them in both directions and create two SAME_AS relationships between the nodes.

Example 9-6. Creating SAME_AS relationships between nodes matching on strong IDs

MATCH (p1:Person), (p2:Person)
WHERE p1.source <> p2.source
AND (p1.ssn = p2.ssn OR p1.passport_no = p2.passport_no)
AND id(p1) > id(p2)
CREATE (p1)-[:SAME_AS { ssn_match : p1.ssn = p2.ssn,
passport_match : p1.passport_no = p2.passport_no}]->(p2)

The script in Example 9-7 shows an implementation of step 2, taking care of the weak identifiers. The m_fullname property is a weak identifier that was created by amalgamating data across sources and by standardizing all name information available. Normally, a match on the name is not sufficient to derive that two persons are the same. That’s why it is treated as a secondary identifier, and a SIMILAR relationship is created only when a match above threshold is found. In Example 9-7, one standard string similarity metric called Jaro–Winkler distance (https://oreil.ly/uQLqE) is used, and when that metric is below 0.2 (depending on the use case), the relationship is created and annotated with a similarity metric.

Example 9-7. Creating similar relationships between nodes matching on weak IDs

MATCH (p1:Person), (p2:Person)
WHERE NOT (p1)-[:SAME_AS]-(p2)
AND p1.source <> p2.source
AND id(p1) > id(p2)
AND apoc.text.jarowinklerDistance(p1.m_fullname, p2.m_fullname) < 0.2
CREATE (p1)-[:SIMILAR { sim_score : 1 - apoc.text.jarowinklerDistance(p1.m_fullname, p2.m_fullname)}]->(p2)

In Example 9-7 the metric is inverted because it measures distance instead of similarity, so to trigger the creation of the relationship, the actual value needs to be under a given distance value instead of over threshold as stated earlier.

The similarity score (sim_score) used to qualify the SIMILAR relationship is created by subtracting the Jaro–Winkler distance from 1. It is important to keep consistent semantics in the score used in this metric to make them comparable and composable later on. The script in Example 9-7 sets a score between 0 and 1.0. The higher the score, the stronger the similarity.

Step 3 is about filtering detected similarities based on weak identifiers (those materialized by SIMILAR relationships) by discarding the ones that exist between entities with discrepancies in the strong identifier features. This is what the Cypher script in Example 9-8 implements.

Example 9-8. Removing similar relationships between nodes matching on weak IDs when they differ on strong ones

MATCH (p1:Person)-[sim:SIMILAR]->(p2:Person)
WHERE p1.ssn <> p2.ssn OR p1.passport_no <> p2.passport_no
DELETE sim

Step 4 applies a correcting factor to the weights in the SIMILAR relationships. The code in Example 9-9 provides an example of this. For every pair of nodes at both ends of a SIMILAR relationship, if there is a reasonable similarity on the year of birth (m_yob, a nonidentifying feature in this case), then the similarity score will be adjusted up or down.

The logic in steps 3 and 4 can also be implemented together with step 2 and, in some cases, achieve an improvement in performance by running a single pass on the data. The disadvantage would be the lack of detailed traceability of the effect of each step. In this chapter, the steps are separated for clarity.

The logic in Example 9-9 is based on an absolute threshold (abs(p1.m_yob - p2.m_yob) > $yob_threshold). If the years of birth are not too dissimilar, the similarity score is increased by 10%, but if the difference is too significant, then the score is decreased by 10%. The adjustment function can be as sophisticated as you need for your use case.

Example 9-9. Boosting or damping similar relationships between nodes matching on weak IDs when they differ on other features

MATCH (p1:Person)-[sim:SIMILAR]->(p2:Person)
WITH sim, abs(p1.m_yob - p2.m_yob) AS yob_diff
SET sim.sim_score = sim.sim_score * CASE WHEN yob_diff > $yob_threshold THEN .9 ELSE 1.1 END

Step 5 removes the SIMILAR relationships that, after applying the correcting factor in the previous step, would result in a similarity score below acceptable. The code in Example 9-10 shows how this can be implemented straightforwardly using Cypher.

Example 9-10. Removing similar relationships between nodes matching on weak IDs when below minimum score

MATCH (p1:Person)-[sim:SIMILAR]->(p2:Person)
WHERE sim.sim_score < $sim_score_threshold
DELETE sim

The result of processing all five steps produces the graph in Figure 9-1.

Figure 9-1. Graph result of applying the matching rules

It’s worth mentioning that after the application of step 2, additional SIMILAR relationships were created, which were subsequently removed when executing step 3—for example, the nodes representing the individuals named Husein Sprull and Hana Sprull. On execution of step 2, a relationship would be created based on the similarity in their names, which would later be removed in step 3 due to the mismatch in their Social Security numbers. This process is shown in Figure 9-2.

Figure 9-2. Relationship of type SIMILAR added and subsequently removed

In the next section, the graph in Figure 9-1 will be analyzed topologically to identify related entities.

Build/Update a Persisted Record of Master Entities

Section titled “Build/Update a Persisted Record of Master Entities”

Once the set of related entities has been determined and the relationships made explicit in the graph, the final step is to create a persisted representation of what’s typically called master entities. Essentially, this means detecting sets of connected nodes in the graph either through SAME_AS or SIMILAR relationships resulting from applying the matching rules.

All nodes in a set form a connected component and are equivalent to a unique entity. Detecting such sets is what the Weakly Connected Components (WCC) algorithm does. The adjective weakly comes from the fact that the algorithm works on undirected graphs. This nicely fits the objective of this exercise because the direction of both SAME_AS and SIMILAR relationships is irrelevant, as both are symmetric.

You can see how this can be implemented using the concepts from Chapter 6. A prerequisite to the application of any algorithm is the creation of an in-memory projection of the subgraph to be used. This is what the code in Example 9-11 does.

Example 9-11. Creating a projection on person nodes and SIMILAR and SAME_AS relationships

CALL gds.graph.project(
'identity-wcc',
'Person',
['SAME_AS', 'SIMILAR']
)

The projected graph is added to the catalog under the name identity-wcc and will include all nodes of type Person and all relationships of type SAME_AS and SIMILAR. A first execution of the WCC algorithm in stream mode (streaming results but not persisting anything in the graph) can be executed with the Cypher fragment in Example 9-12. Note that the invocation of an algorithm refers to the projected graph by its name in the catalog.

Example 9-12. Running the WCC algorithm to identify nodes in the same identity group

CALL gds.wcc.stream('identity-wcc')
YIELD Node, componentId
WITH gds.util.asNode(Node) AS person, componentId AS golden_id
RETURN golden_id, person.m_fullname, person.passport_no, person.ssn
ORDER BY golden_id

The results produce an identifier per connected component. For readability, some details about each node in the component are added. You can see that in Example 9-13.

Example 9-13. Results of running the WCC algorithm

golden_idperson.m_fullnameperson.passport_noperson.ssn
0“sidney joanne bernardy”“A465901”null
0“syd j bernardy”null“252-13-7091”
0“sidney bernardy”“A465901”“252-13-7091”
1“cherise gosnall”null“422-45-7305”
1“c gosnall”null“422-45-7305”
1“cherish gosnall”“BS945813”“422-45-7305”
4“jon pedracci”“TH834501”null
4“jonathan pedracci”null“581-96-2576”
5“hana sprull”null“465-63-9210”
7“ernestine ouchterlony”“CF3586”“557-21-3938”
9“husein sprull”“FG45867”“123-03-8992”

Once you’re happy with the results, you can persist them in the knowledge graph. You could simply use the write version of the algorithm (gds.wcc.write), which annotates each node with the connected component identifier, and then use that to create master entities.

Instead, the Cypher script in Example 9-14 uses the output of the stream version of the algorithm to create a customized persisted representation of the connected components. The subgraph created is itself a representation of the master entity (the golden record). The same script connects all matched records to the master entity, enabling traceability.

Example 9-14. Creating entity nodes (golden records) from the result of the WCC algorithm and linking to original ones

CALL gds.wcc.stream('identity-wcc')
YIELD Node, componentId
WITH gds.util.asNode(Node) AS person, componentId AS golden_id
MERGE (pg:PersonMaster { uid: golden_id })
ON CREATE SET pg.fullname = person.m_fullname,
pg.ssn = person.ssn, pg.passport_no = person.passport_no
ON MATCH SET pg.ssn = coalesce(pg.ssn, person.ssn),
pg.passport_no = coalesce(pg.passport_no, person.passport_no)
MERGE (pg)-[:HAS_REFERENCE]->(person)

Once the entity nodes have been created and linked to the original references, the identity graph will resemble Figure 9-3.

Figure 9-3. Each connected component defines a master entity

Graphs like Figure 9-3 can be queried to produce an aggregated view of a master entity, including all details by source. This is shown in Example 9-15.

Example 9-15. Querying the master entities and producing a detailed summary of all the related references

MATCH (p:PersonMaster)-[:HAS_REFERENCE]->(ref)
WHERE p.passport_no = 'A465901'
WITH p, collect( { source: ref.source , details : properties(ref)}) AS refs
RETURN { master_entity_id : p.uid, references: refs }

For interoperability, you can also produce the JSON serialization of the results directly from the Cypher query, as in Example 9-16.

Example 9-16. JSON serialization of an aggregated view of a master entity

{
"master_entity_id": 0,
"references": [
{
"source": "ds2",
"details": {
"m_fullname": "sydney joanne bernardy",
"system_id": "2_1",
"m_yob": 1979,
"name": "Bernardy, Sydney Joanne",
"passport_no": "A465901",
"source": "ds2",
"age": "44"
}
},
{
"source": "ds1",
"details": {
"m_fullname": "sidney bernardy",
"full_name": "Sidney Bernardy",
"system_id": "1_1",
"m_yob": 1979,
"passport_no": "A465901",
"source": "ds1",
"yob": "1979",
"email": "[email protected]",
"ssn": "252-13-7091"
}
},
{
"source": "ds3",
"details": {
"m_fullname": "syd j bernardy",
"dob": "1979-05-13",
"system_id": "3_1",
"m_yob": 1979,
"last_name": "Bernardy",
"source": "ds3",
"first_name": "Syd J",
"email": "[email protected]",
"ssn": "252-13-7091"
}
}
]
}

There are two final important things to note.

The data sources to which the entity resolution is applied tend to be living and change over time. The process is rarely a one-off exercise and will usually require future iterations. In cases where the data sets being deduplicated are large, it is common to get the deltas (new elements and removed ones) at regular intervals instead of full new versions of the data sets. This complicates things because it means that the addition (or removal) of new data points from a data set may affect previous matches. It may also create new or alter existing connected components. To accommodate this, a preliminary step is needed where any removed elements in the delta are removed from the graph.

It is often helpful to use information from the graph to improve entity resolution results. The approach can be extended to include properties in relationships or in neighboring nodes. You can also include structural metrics like the degree, centrality, or other graph measure. In fact, one of the most powerful things about graphs is that all these features are automatically available for entity resolution.

The absence of strong identifiers in the data will force you to do more sophisticated work on the weak identifiers and the nonidentifying features. These will often be text descriptions for which only the string similarity metrics have been proposed so far. What other options do graphs offer?

The Amazon-Google product catalog data set (https://oreil.ly/XPcn1) provides a good setup for showing how to solve this problem. The data set contains 1,363 product descriptions from Amazon.com and 3,226 from Google products. The common attributes between the two data sources are product name, product description, manufacturer, and price. The data is loaded in the usual way from CSV files in Example 9-17.

Example 9-17. Loading product data

LOAD CSV WITH HEADERS FROM "file:///amz.csv" AS row
CREATE (p:Product { sid: row.id }) SET p.source = "AMZ", p += properties(row);
LOAD CSV WITH HEADERS FROM "file:///ggl.csv" AS row
CREATE (p:Product { sid: row.id }) SET p.source = "GGL", p += properties(row);

The preparation phase tokenizes the product name by breaking it into words after lowercasing and removing all nonalphanumeric characters from the text (replace(tolower(p.name),"[^a-zA-Z0-9]"," ")). In this example, the split function is used, which means that a word is anything separated from other words by a whitespace. Other methods could equally be used, like tokenizer functions in natural language software packages (such as NLTK, spaCy, Hugging Face, and others). The complete Cypher script is in Example 9-18.

Example 9-18. Normalizing and extracting words from all products

CREATE INDEX FOR (w:Word) ON w.txt;
MATCH (p:Product { source : "GGL" })
UNWIND [x in split(apoc.text.replace(tolower(p.name),"[^a-zA-Z0-9]"," ")," ") WHERE x <> "" ] AS txt
MERGE (w:Word { txt: txt }) MERGE (p)-[:includes]->(w);
MATCH (p:Product { source : "AMZ" })
UNWIND [x in split(apoc.text.replace(tolower(p.title),"[^a-zA-Z0-9]"," ")," ") WHERE x <> "" ] AS txt
MERGE (w:Word { txt: txt }) MERGE (p)-[:includes]->(w);

The resulting graph contains the nodes representing the products that need to be deduplicated as well as the ones representing the tokens (the words). This forms a network like the one seen in the excerpt in Figure 9-4. You can see how some tokens are shared across products.

Figure 9-4. Words extracted from product titles forming a network connecting products

You can now execute a structural similarity algorithm on the graph in Figure 9-4. The Node Similarity algorithm compares a set of nodes based on the nodes they are connected to. Two nodes are considered similar if they share many of the same neighbors. In this case, that means sharing words in the product name. The algorithm computes pair-wise similarities based on either the Jaccard metric (also known as the Jaccard Similarity Score) or the overlap coefficient (also known as the Szymkiewicz–Simpson coefficient).

The implementation requires the creation of the in-memory projected graph (Example 9-19). This is a bipartite graph including products and words. Its implementation is highly memory optimized so that billions of graph elements can be performantly processed on commodity hardware.

Example 9-19. Creating projection by matching on product title

CALL gds.graph.project(
'identity-sim',
['Product', 'Word'],
['includes']
);

The projection is followed by the execution of the algorithm where it is possible to set a similarity cutoff threshold (similarityCutoff: 0.8), discarding all cases where similarity is not high enough to be acceptable. By default, the gds.nodeSimilarity algorithm uses the Jaccard metric, but it is possible to override that and use the overlap metric instead (just add the parameter similarityMetric: 'OVERLAP'). The code in Example 9-20 uses the stream version of the algorithm, producing the results in the Example 9-21 table.

Example 9-20. Running similarity algorithm on projection

CALL gds.nodeSimilarity.stream('identity-sim', { similarityCutoff: 0.8 })
YIELD node1, node2, similarity
WITH similarity, gds.util.asNode(node1) AS node1, gds.util.asNode(node2) AS node2
WHERE node1.source = "GGL" AND node2.source = "AMZ"
RETURN similarity AS tk_sim,
apoc.text.jarowinklerDistance(node1.name, node2.title) AS str_sim,
node1.name AS Prod1,
node2.title AS Prod2

The results are shown in Example 9-21. An additional column with string similarity score calculated using the Jaro–Winkler distance has been added to show that the token-based approach is more robust than a string-similarity one. Something as benign as a formatting change in a product name (see last record: apple apple mac x server 10 4 7 10 client versus mac os x server v10.4.6 10-client) could have a significant impact on the string similarity and would be missed by setting a high threshold, depending on use case.

Example 9-21. Entity-matching results from running similarity algorithm

tk_simstr_simProd1Prod2
0.80.7969“allume internet cleanup 3.0”“internet cleanup 3.0”
0.80.7831“marware project x project management software”“project x project management software”
0.80.7703“allume morpheus photo animation suite”“morpheus photo animation suite”
0.80.7627“mobile media converter (pc) pinnacle”“pinnacle mobile media converter”
0.80.7593“extensis suitcase fusion 1u box”“suitcase fusion 1u box”
0.80.7423“sp linux we 50 lic/cd 3.0c”“hp sp linux we 50 lic/cd 3.0c (t3586a )”
0.80.7406“serverlock manager - 100 servers”“watchguard serverlock manager (100 servers)”
0.80.7234“print shop deluxe 21”“broderbund print shop 21 deluxe”
0.80.6965“apple apple mac os x server 10 4 7 10 client”“mac os x server v10.4.6 10-client”

The next step would be the creation of the SIMILAR relationships (because the product name is a weak identifier). The Cypher script in Example 9-22 takes care of this by setting the similarity score as the value returned by the algorithm.

Example 9-22. Matching using product title

CALL gds.nodeSimilarity.stream('identity-sim', { similarityCutoff: 0.8 })
YIELD node1, node2, similarity
WITH similarity, gds.util.asNode(node1) AS node1, gds.util.asNode(node2) AS node2
WHERE node1.source = "GGL" AND node2.source = "AMZ"
MERGE (node1)-[:SIMILAR { sim_score : similarity }]->(node2)

From here on, the algorithm will continue to build the graph where the connected components yield matching entities.

Case Study: The Meredith Corporation Identity Graph

Section titled “Case Study: The Meredith Corporation Identity Graph”

Meredith Corporation was a media conglomerate with $3.2 billion in annual revenue. With over 30 top consumer brands including Parents, People, Real Simple, and Coastal Living, Meredith’s digital presence reached more than 180 million users a month across dot-coms, apps, websites, podcasts, and video.

Meredith sought to give users just the right content throughout the day, personalized just for them. But that meant really knowing your user—a challenge when most people don’t log in.

Meredith identified anonymous users through unique cookies that drop on the user’s device. But cookie loss, diverse devices, and browsers that block cookies by default increased the difficulty of getting a 360-degree view. Even when they work, cookies have a short lifespan.

Graph queries offer rapid answers no matter how large your graph is. But if you are running the same query over and over to build up user profiles, there is a better way: run a graph algorithm over the entire graph.

The Meredith data science team chose the WCC algorithm to identify unique subgraphs (connected components) within the larger graph. In production, the Meredith Identity Graph incorporated more than 20 months of user data from both first- and third-party sources. The database had more than 4.4 terabytes of data for 30 billion nodes, 67 billion properties, and 35 billion relationships.

The average length of touch points exploded from 14 days with a cookie to 241 days with user profiles. Average visits increased from 4 per cookie to 23.8 per profile.

Nearly 350 million profiles that would have been considered unique individuals with different interests and patterns were consolidated into 163 million richer and more accurate profiles. A high-definition view of user interests and preferences fueled stronger models, which led to more relevant content and more users returning over time. It created a virtuous cycle.

Meredith commented, “We basically have increased our understanding of a customer by 20 to 30% by looking at how the data connects over time, rather than just looking at individual cookies themselves. Instead of advertising in the dark, we now better understand our customers, which translates into significant revenue gains and better-served consumers.”

If you are implementing your embedded knowledge graph using petgraph and redb as discussed in previous chapters, you can implement entity resolution logic natively in Rust.

While you don’t have access to Cypher’s MERGE and MATCH statements, you can execute the same logical steps—identifying strong/weak identifiers, calculating string similarities, and running Weakly Connected Components (WCC)—with extremely high performance in memory.

Rust has excellent crates for text processing and similarity. For Jaro-Winkler distance (used in step 2 of our methodology), you can use the strsim crate.

use strsim::jaro_winkler;
fn is_similar(name1: &str, name2: &str, threshold: f64) -> bool {
let similarity = jaro_winkler(name1, name2);
similarity >= threshold
}

Finding Connected Components (WCC) in petgraph

Section titled “Finding Connected Components (WCC) in petgraph”

Once you have iterated through your data and added SAME_AS or SIMILAR edges to your petgraph structure, you need to extract the master entities. In Neo4j, we used the gds.wcc algorithm. In petgraph, you can use the kosaraju_scc (Strongly Connected Components) or tarjan_scc algorithms. For an undirected graph (which is what SAME_AS and SIMILAR represent logically), SCC algorithms will naturally find the weakly connected components.

Alternatively, you can use petgraph::algo::connected_components (if using an undirected graph type) or simply run a Breadth-First Search (Bfs) to manually extract components.

Example 9-23. Extracting Golden Records using WCC in petgraph

use petgraph::graph::{UnGraph, NodeIndex};
use petgraph::algo::tarjan_scc;
use std::collections::HashMap;
// Assume we have an undirected graph where edges represent SAME_AS or SIMILAR
#[derive(Debug, Clone)]
pub struct PersonNode {
pub id: String,
pub name: String,
}
pub fn generate_golden_records(graph: &UnGraph<PersonNode, ()>) -> HashMap<usize, Vec<String>> {
// tarjan_scc returns a vector of components.
// Each component is a vector of NodeIndices that belong to the same cluster.
let components = tarjan_scc(graph);
let mut golden_records = HashMap::new();
// Iterate through the identified components
for (golden_id, component) in components.into_iter().enumerate() {
let mut references = Vec::new();
for node_idx in component {
let person = &graph[node_idx];
references.push(person.id.clone());
}
// Save the component ID mapping to the original record IDs
golden_records.insert(golden_id, references);
}
golden_records
}

By extracting these components, you can easily map them back into a new structure representing your PersonMaster entities, which can then be serialized and persisted back to redb or exposed via an API. The logic remains the same as the Neo4j approach, but executing it in compiled Rust over an in-memory petgraph allows you to process millions of records in a fraction of a second.

Identity is a key pillar for connecting knowledge graphs to the real world. In this chapter, you’ve learned about strong and weak identifiers for data. You’ve also discovered how, by using knowledge graphs and graph algorithms, a set of weak identifiers can be aggregated in a strong identifier. With these techniques, you can take on even unruly data sets and truly master that data. Whether that’s by connected components, node similarity, or custom graph matching, you have the necessary tools at your disposal. From here, with data quality much improved through mastering, you’ll move onto large-scale pattern-matching graphs.