Semantic Search and Similarity
local graph
Chapter 12 — Semantic Search and Similarity
Section titled “Chapter 12 — Semantic Search and Similarity”A good proportion of data available in the world is in the form of documents—documents created by humans for consumption by humans and therefore expressed in natural language. But natural language is not easy to exploit programmatically because it does not have a well-defined structure like a table (database or CSV file) or a hierarchy (JSON or XML document). Any automated use of a natural language document will require some preprocessing to extract structured information from it. If you want to go past the basics of text processing (word count, text-based analysis), this can only be achieved using technology called natural language processing (NLP). In this chapter, you will see how the types of structures that result from applying NLP techniques fit naturally into a graph structure and how building knowledge graphs from unstructured data enables more sophisticated exploitation.
Search over Unstructured Data
Section titled “Search over Unstructured Data”The first obvious way you want to make programmatic use of the content in natural language documents is to enable search. Search is an area that has had an incredible recent history. In its earliest days, just two decades ago (and surprisingly still today for many services), a search engine would have been a simple index over a set of natural language documents, sometimes even human curated. To use it, you had to type a keyword and hope it matched an index term. This does not particularly help, given the many lexical variations in most human languages (a search for the term country would ignore potentially relevant documents containing its plural countries). If you add to this inherent complexity of natural languages other elements like the use of alternative spellings (sometimes due to typos), abbreviations, and acronyms, the task does not get any easier. The consequence is that search results were (are) often less than good.
The second part of the search problem is ranking the results. In this basic scenario, the engine cannot do better than sorting by simple relevance metrics like number of appearances of the search term.
Graphs Supercharge Search
You use search every day: to find documents on your hard drive, a product in an online shop, a song on your favorite music streaming service, or virtually anything on the web using a search engine.
Google has revolutionized Web search on both fronts over the years, first with the PageRank algorithm, used to rank search results (web pages) in the Google search engine by leveraging existing connections (hyperlinks) between pages. With PageRank, relevance of web pages to queries is based on whether the pages contain the search term as well as how many relevant pages link to it.
Years later, Google also introduced the use of knowledge graphs to enhance search. Google search today is underpinned by a series of sophisticated algorithms and data, but both PageRank and the Google Knowledge Graph remain fundamental for making sense of the web today.
Search engines have evolved over the years. Keyword-based search has been enhanced with features like wildcard searches, fuzzy searches, and the possibility of combining keywords using logical expressions with different ways of ranking results (like term frequency–inverse document frequency).
The use of knowledge graphs to complement index-based search makes modern engines far superior. Knowledge graphs capture the “intelligence” required to resolve synonyms, adjacent keywords, or domain-related concepts. In fact, they can take search into the territory of question answering. Not only can they return semantically relevant documents for a given search, but they can also be used to provide sophisticated responses to natural language questions. This chapter will cover the first problem, and the second will be explored in Chapter 13.
From Strings to Things: Annotating Documents with Entities
Section titled “From Strings to Things: Annotating Documents with Entities”The natural language text in documents is a human way of conveying information by describing entities and relationships between them. But the same entities and relationships can be described in many different ways because human language is very rich (but also ambiguous and contextual). That’s why basing any kind of automated processing (search, in this case) of the documents on the text representation is both inaccurate and inefficient as hinted at in the previous section. You need to move this processing to a higher level of abstraction. In fact, the goal is to search for “things not strings” (as described in the Google blog by Amit Singhal: “Introducing the Knowledge Graph: Things, Not Strings” (https://oreil.ly/fRkjH)).
The first step to achieve this is to apply the most basic type of processing of natural language: the extraction of the entities “hidden” in the text. This process is often called text annotation, and the NLP technique is named-entity recognition (NER).
To understand what NER will do for us, take the example of a document that contains the sentence “The New York Times is a daily newspaper and its headquarters is on the west side of Midtown Manhattan in New York City.” NER will unambiguously uncover that both an organization “The New York Times” and a location “New York” are mentioned in the text even though both are described with the same words. Making these results explicit in a knowledge-graph-powered search engine would then make it possible to do both location- and company-based searches, whereas a text-based search would only be able to find a match on the text “New York” but would not be able to distinguish whether the text refers to one or the other.
To illustrate the application of NER for building a knowledge graph that enables entity-based search, see Table 12-1. It contains a list of documents (articles) with their titles and summaries.
Table 12-1. A list of articles to put in a semantic search knowledge graph
| Article list |
|---|
| Title: Twitter chair Patrick Pichette joins graph data platform Neo4j board of directors. Fragment: Pichette is currently a partner at Inovia Capital and is also currently chair of commerce platform Lightspeed. His 30 years of financial and operating expertise includes roles at Google, Sprint Canada and Bell Canada, with a focus on digital transformation and hyper-growth. According to Pichette, “Neo4j’s graph technology offers a truly unique solution to solve some of the world’s most complex challenges, with a clear focus on promoting transparency and positive social change.” author: Digital Nation Staff url: https://www.itnews.com.au/digitalnation/news/twitter-chair-patrick-pichette-joins-graph-data-platform-neo4j-board-of-directors-572498 |
| Title: JupiterOne Unveils Starbase for Graph-Based Security Fragment: JupiterOne has announced Starbase, an open source tool for security analysts to collect information about the organization’s assets and their relationships and pull them into an intuitive graph view for cyber asset management. The graph data model, based on open source graph data platform Neo4j, makes it easier to see relationships between different assets and to perform complex relationship analysis, the company said in a statement. ”As a CSO, I’m a big advocate of bringing graph-based technology to security, given its power to reshape how we think about security threat defense” said Sean Catlett, CSO at Slack. author: Dark Reading Staff url: https://www.darkreading.com/dr-tech/jupiterone-unveils-starbase-for-graph-based-security |
You will need two basic components, as depicted in Figure 12-1: a software package that can carry out the entity extraction from the natural language text in the article collection and a graph platform to store the results of the process as connected entities.
For this first example, you will use Hugging Face (https://huggingface.co) to take care of the entity extraction and Neo4j (http://neo4j.com) for the storage and analysis of the results in the form of a knowledge graph.
Figure 12-1. Extracting entities from natural language text and storing them in a graph database
Under its Token Classification subtasks, Hugging Face includes NER. Its use is quite straightforward if you stick to the defaults. Example 12-1 shows a Python code snippet that extracts the entities from the title of the first of the articles in the list. In a complete example, you would iteratively apply this type of analysis to all articles in your collection.
Example 12-1. Extracting entities from natural language text using Python
from transformers import pipeline
ner_pipe = pipeline("ner", aggregation_strategy="simple")
title = """Twitter chair Patrick Pichette joins graph dataplatform Neo4j board of directors."""
for entity in ner_pipe(title): print(entity)When not overridden, the pipeline uses the bert-base-NER model, which performs great in the example with general English language. If you are working on a very specific domain and your natural language documents use highly technical terms, you will want to use an NER model trained specifically for that domain. Both the creation and the use of a custom model is beyond the scope of this book, but the Hugging Face documentation (https://oreil.ly/YGqm4) is very useful.
The output from the code is shown in Example 12-2 and is basically the list of entities identified in the text, with their types and a score associated with each of them.
Example 12-2. Entities extracted
{'entity_group': 'ORG', 'score': 0.9961534, 'word': 'Twitter', 'start': 0, 'end': 7}{'entity_group': 'PER', 'score': 0.9972605, 'word': 'Patrick Pichette', 'start': 14, 'end': 30}{'entity_group': 'ORG', 'score': 0.8314789, 'word': 'Neo4j', 'start': 62, 'end': 67}Because entities can be of different types and not all are equally important in the context of the natural language text being analyzed, it is quite common for NER processors to return the following in addition to a list of entities:
type
Is it a person? Is it a location? Is it an organization? The set of categories will depend on the specific model used. The bert-base-NER distinguishes four types of entities: location (LOC), organization (ORG), person (PER), and miscellaneous (MISC).
salience The relative importance in the text analyzed or, in other words, the entity’s relevance. Is the entity central to the text (higher score/salience), or is it just mentioned tangentially (lower score/salience)?
Now that you know how to extract entities from natural language, you can store these entities along with the information about the articles they come from. When doing that, you will make the connection between articles and entities explicit and weighted (the salience) and form a knowledge graph like the one in Example 12-3.
As in the previous example, for simplicity the code only shows the process for a single entry in the article list (the title, the author, the URL, and a fragment of text). A complete version would iterate over the list of articles and invoke the following logic for each of them.
Example 12-3. Writing entities to a knowledge graph
from neo4j import GraphDatabase
driver = GraphDatabase.driver("bolt://your.db.ip:7687", auth=("neo4j", "pwd"))
title = "the title of the article"fragment = "article fragment"author = "the author of the article"url = "https://the.url.of.the.article"
entity_list = []for entity in ner_pipe(title + fragment): entity_list.append(entity)
cypher_query = '''MERGE (a:Article { url:$url}) ON CREATE SET a.title= $title, a.text= $frgMERGE (p:Person { name: $author})MERGE (a)-[:has_author]->(p)WITH a UNWIND $entityList AS entityMERGE (e:Entity { name: entity.word , type: entity.type })MERGE (a)-[:references { salience: entity.score }]->(e)'''
with driver.session(database="neo4j") as session: session.write_transaction( lambda tx: tx.run(cypher_query, url=url, author=author, title=title, frg=fragment, entityList=[{ "word": x["word"], "type":x["entity_group"] } for x in entity_list]) )
driver.close()This code produces a knowledge graph like the one in Figure 12-2. Such a graph enables a much richer use of the data in the documents.
Figure 12-2. Graph with explicit entities sourced from articles
Having a collection of entities that make the content of the articles explicit substantially enriches the options for search. You can now list the entities mentioned in the articles, or in other words, answer the question “What is this document about?” with the simple Cypher query shown in Example 12-4.
Example 12-4. A Cypher query shows entities referenced in articles
MATCH (a1:Article)-[:references]->(e:Entity)WHERE a1.url = $urlRETURN e.name AS entityName, e.type AS entityTypeThe exact same pattern also answers the inverse question “Which articles mention this entity?” The complete Cypher would be the one shown in Example 12-5.
Example 12-5. A Cypher query shows articles that reference specific entities
MATCH (a:Article)-[:references]->(e:Entity)WHERE e.name = $entityName AND e.type = $entityTypeRETURN a.url AS articleLink, a.title AS articleTitleThis technique also helps determine popularity and trends at the entity level, as opposed to the much less meaningful word level. Think of an entity frequency metric versus a basic word count. You can aggregate mentions of entities to compute the most or least popular entities of all time or over a particular time range. You can even analyze trends for entities over time and see how their popularity evolves, just by counting how frequently they appear in documents over a given time period.
Example 12-6 shows how to get the data points to populate a monthly time series with the frequency of the appearance of a given entity in articles published each month.
Example 12-6. A Cypher query to find popular entities over a period of 12 months
MATCH (c:Entity { name: $entityName, type: $entityType })WITH c, date() - duration("P1Y") AS startdateUNWIND range(0,11) AS incrementMATCH (c)<-[:references]-(a:Article)WHERE startdate + duration("P" + (increment - 1) + "M") < a.published < startdate + duration("P" + increment + "M")RETURN startdate + duration("P" + increment + "M") AS date, count(a)Navigating the Connections: Document Similarity for Recommendations
Section titled “Navigating the Connections: Document Similarity for Recommendations”You have seen how document annotation surfaces a graph that enables search at a higher level of abstraction (entities versus words). Now you will see that the analysis of the structure of this graph, as Figure 12-3 shows, can help you uncover similarities between documents with very high precision.
Figure 12-3. Enabling navigation from one document to another via entities
Content-based recommender systems are centered on the features of the items to recommend—“You may also like X”—as opposed to collaborative filtering ones that focus on the analysis of the behavior of the consumers—“Customers like you also bought/read/watched X.” If you are browsing for desks on your favorite furniture ecommerce and you click on a white solid wood one, it should not surprise you if you see on the side of your screen a list of “similar items” with more white wood desks or items that share a good number of features with the one you are looking at. It’s easy to extrapolate this approach: the items are the articles, and the features are the entities that you extracted from them.
All you need now is a systematic way to combine the feature matches to come up with a similarity metric. Ordering the results by that metric will give you the top $n$ elements to recommend. In the case of the furniture ecommerce, it might be tricky to determine whether a match on the color is more important than a match on the material, so the weights would probably be determined by domain experts. In this case, the salience of the entity in a document gives a useful hint.
Taking this step by step, the starting point is that articles are related to each other by the entities they share. Given two articles, a simple graph pattern like the one shown in Example 12-7 will find the collection of entities that are referenced in both of them.
Example 12-7. A Cypher query shows entities that are referenced in both articles
MATCH (a1:Article)-[:references]->(e:Entity)<-[:references]-(a2:Article)WHERE a1.url = $url1 AND a2.url = $url2RETURN e.name AS entityName, e.type AS entityTypeThe Cypher query takes only the URLs (unique identifiers) of the articles. In the example, the results would show that for the two articles in Table 12-1, Neo4j Inc. is the only entity that happens to relate to both.
This simple pattern can be extended to compute the similarity metric for any pair of documents. In the query in Example 12-8, the similarity is defined as the weighted sum of entities shared between two articles. The bigger the entity overlap, the greater the similarity between the articles. But not all entities are counted in the same way—remember that the relationships between articles and entities are weighted with the salience of the entity in that particular document.
Example 12-8. A Cypher query calculating a similarity metric between a pair of articles
MATCH (a1:Article)-[r1:references]->(e:Entity)<-[r2:references]-(a2:Article)WHERE a1.url = $url1 AND a2.url = $url2RETURN sum(r1.salience * r2.salience) AS similarity_metricThis is a very simple graph pattern but an extremely powerful metric that will help you offer a recommendation about what to read next, based on the assumption that the reader will want to continue reading about similar topics.
Nearly as important as having a way of measuring how similar two items are is a precise description of how exactly they are related because that will help you produce not only a relevant recommendation but also an explainable one. It turns out that it is easily in reach of the knowledge graph. Example 12-9 shows the complete recommendation query returning the top five similar articles along with an enumeration of the shared entities that explain the similarity.
Example 12-9. A Cypher query finds similar articles computing the similarity metric on the fly (at query time)
MATCH (a1:Article)-[r1:references]->(e:Entity)<-[r2:references]-(recommendation)WHERE a1.url = $url1RETURN recommendation, sum(r1.salience * r2.salience) AS similarity_metric, collect(e) AS explanationORDER BY similarity_metric DESC LIMIT 5In some cases, it will make sense to compute the recommended set on the fly as in Example 12-9, but sometimes you will want to enrich the graph by materializing the similarities between articles with a new weighted relationship directly connecting similar articles where the weight in the relationship would encode the similarity metric computed with the previous formula. This approach is described visually in Figure 12-4.
Figure 12-4. Creating a new weighted similarity relationship between articles
The creation of such relationship would require just a minor change to the previous query, as seen in Example 12-10.
Example 12-10. A Cypher query creates a new weighted similarity relationship between articles
MATCH (a1:Article)-[r1:references]->(e:Entity)<-[r2:references]-(a2:Article)WITH a1, a2, sum(r1.salience * r2.salience) AS similarity_metricMERGE (a1)-[:similar { metric: similarity_metric }]->(a2)If you want to run this type of query on a large graph, you’ll want to batch it instead of running it in a single transaction. You can achieve this with the Cypher clause CALL { ... } IN TRANSACTIONS or using the periodic execution methods in the APOC library (https://oreil.ly/lzym6).
Once the metric is persisted in the graph, generating recommendations based on a selected article becomes a lot simpler, as shown in Example 12-11.
Example 12-11. A Cypher query finds similar articles using a precomputed similarity metric
MATCH (a1:Article)-[r:similar]-(recommendation)WHERE a1.url = $url1RETURN recommendation, r.metric AS similarity_metricORDER BY similarity_metric DESC LIMIT 5The Cold Start Problem
Section titled “The Cold Start Problem”Document similarity is useful for recommending what to show, read, or buy next, but it requires some context, something to anchor your queries on. The previous recommendations selected an article (or a set of recently read articles) as the anchor points.
But what about a “cold start” (https://oreil.ly/ssxQg) where there are no anchor points in your knowledge graph? How could you generate an initial recommendation, for example, to populate a home page and overcome the cold start problem? In that case, it might be reasonable to display currently trending topics. Those can be found using the query shown in Example 12-12, which is similar to the trend analysis query in Example 12-6.
Example 12-12. A Cypher query that ranks the most popular topics over the last six months
MATCH (c:Concept)<-[:refers_to]-(a:Article)WHERE date() - duration("P6M") < a.datetime < date()RETURN c.label, count(a) AS freq LIMIT 10Example 12-12 doesn’t directly provide a semantically rich answer to a question since at cold start there is no such question. It does provide some way of making forward progress into the world of linked entities and semantic search.
While not as computationally cheap as the approach in Example 12-12, there are other ways you could lessen the effects of the cold start problem. For example, you could run a similarity algorithm (as per Chapter 5) on the existing graph. The results of that algorithm would immediately be able to suggest similar things to the user, once the user anchors to a particular topic/article/etc. Moreover, with careful design, the similarity algorithm can be run periodically (on a secondary server), with its results being written directly into the production graph.
Making the Annotation Semantic with an Organizing Principle
Section titled “Making the Annotation Semantic with an Organizing Principle”Document annotation based on NER has been a significant step in the right direction, but it’s limited in two obvious ways:
-
Entities are not disambiguated. The consequence is that if one of the documents in my collection mentions the United Kingdom and another one does the same using the acronym UK, the NER software will probably successfully identify the entities as locations but will not be able to determine that they both represent the same thing.
-
There are no relationships linking entities and capturing the domain knowledge. To continue the geography-based example, a third document mentioning Wales would have the location entity identified but the fact that there is a
PART_OFrelationship between Wales and the United Kingdom is not known to search/recommendation systems.
The way to overcome these limitations is to match the entities to known entries in an organizing principle to form a semantic knowledge graph. Recall that an organizing principle can be an ontology, a concept scheme, or a vocabulary, and it describes the different entities in a particular domain as well as how they relate to one another.
The adoption of standard organizing principles varies by industry. One of the more prolific ones in this area is the pharmaceutical, health care, and life sciences industry. Examples of well-known and mature organizing principles are Medical Subject Headings (MeSH) (https://oreil.ly/PvtXI), a comprehensive controlled vocabulary for indexing journal articles and books in the life sciences, and the Disease Ontology (https://oreil.ly/EkpOR), a standardized ontology for human disease.
A visual intuition of this idea can be produced as an extension of the image in Figure 12-3 by adding to it an organizing principle. The extra layer would effectively offer new ways to explore the data by bringing in explicit domain knowledge as seen in Figure 12-5.
Figure 12-5. An organizing principle offers additional paths for search and exploration
The process of matching entities to uniquely defined entries in a shared concept scheme is often referred to as named-entity linking (https://oreil.ly/Dmrkk) or entity disambiguation.
This task is often bundled with the entity extraction process and carried out by specifically trained extractors that are aware of the target organizing principle and that generate entities prematched to elements in that organizing principle. When using general-purpose NER engines like the ones described in the previous sections, we will have to apply custom algorithms, often based in heuristics, to connect the entities resulting from the NER with the elements in the organizing principle. That use case will be explained later in the chapter, but first you should understand the more common approach.
For this example, you will use a different natural language package: the Google Cloud Platform (GCP) Natural Language API (https://oreil.ly/fgflu). The GCP Natural Language API includes an entity extraction feature very similar to the one offered by Hugging Face but with one interesting addition: the API adds some metadata to the entities it extracts, including Wikipedia URLs. These URLs will help you to match them to entities in an organizing principle in a nonambiguous way.
Just like in Example 12-1 with Hugging Face, in Example 12-13 you can see a small code fragment that calls the GCP Natural Language API to run entity recognition on the title of one of the articles used in the previous section.
Example 12-13. Python code shows how to call the GCP Natural Language API
from google.cloud import language_v1
client = language_v1.LanguageServiceClient.from_service_account_json('services.json')
text = u"Twitter chair Patrick Pichette joins graph data platform Neo4j board of directors"document = language_v1.Document( content=text, type_=language_v1.Document.Type.PLAIN_TEXT)
response = client.analyze_entities(request={"document": document})
for entity in response.entities: print(entity)When you run this code, you get a list of entities with their type and salience, as shown in Example 12-14. Note that they are returned with some additional metadata that effectively disambiguates them by linking them to Wikipedia entries (other elements like the Google Knowledge Graph ID have been removed for clarity).
Example 12-14. A list of entities with Wikipedia links
name: "Patrick Pichette"type_: PERSONmetadata { key: "wikipedia_url" value: "https://en.wikipedia.org/wiki/Patrick_Pichette"}salience: 0.6320402026176453
name: "Twitter"type_: ORGANIZATIONmetadata { key: "wikipedia_url" value: "https://de.wikipedia.org/wiki/Twitter"}salience: 0.22149702906608582
name: "Neo4j"type_: ORGANIZATIONmetadata { key: "wikipedia_url" value: "https://en.wikipedia.org/wiki/Neo4j"}salience: 0.020158693194389343The solution to the linking problem would be complete if you could find an organizing principle that would include in its elements the same metadata (a reference to the Wikipedia page). Interestingly, some public ontologies and knowledge bases like Wikidata (https://www.wikidata.org) or DBPedia (https://dbpedia.org) are cross-referenced, and they do include the Wikipedia page reference in their elements.
As an example, Example 12-15 shows a fragment of the Wikidata graph describing the entity Neo4j (https://oreil.ly/LnJA4) (identified as wd:Q1628290). The description includes a statement indicating that the Wikipedia page https://en.wikipedia.org/wiki/Neo4j is about (schema:about) that particular entity.
Note that Wikidata uses numeric values to identify all elements in it. Just like Neo4j is identified as wd:Q1628290, it is classified as a graph database, which is itself identified as wd:Q595971.
Example 12-15. A fragment of the code from the Wikidata graph for Neo4j
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .@prefix schema: <http://schema.org/> .@prefix wdp: <http://www.wikidata.org/prop/direct/> .@prefix wd: <http://www.wikidata.org/entity/> .
wd:Q1628290 rdfs:label "Neo4j"@de ; schema:description "graph database implemented in Java"@en ; wdp:P31 wd:Q595971 .
<https://en.wikipedia.org/wiki/Neo4j> schema:about wd:Q1628290 .With these two parts, it’s straightforward to build a semantic knowledge graph, as described in Figure 12-6.
Figure 12-6. Entity disambiguation in two steps using GCP’s Natural Language API and Wikidata
The following example shows a Cypher-only version of this process. You can do that because the APOC library in Neo4j offers wrapper methods that invoke the GCP Natural Language API without having to write any external code as in previous examples in this chapter.
- Import articles as nodes in the graph. The Cypher statement in Example 12-16 parses the list of articles as a CSV file (
articles.csv) with four columns:uri,title,body, anddatetime. It also creates a node for each of the records.
Example 12-16. Loading articles into a knowledge graph
LOAD CSV WITH HEADERS FROM 'file:///articles.csv' AS rowCREATE (a:Article { uri: row.uri})SET a.title = row.title, a.body = row.body, a.datetime = datetime(row.date)- Import the organizing principle into the graph. Assume that the organizing principle is described using any of the common W3C standards: OWL, SKOS or RDFS. You then rely on the
neosemanticslibrary (https://oreil.ly/BvULd) for the import, as shown in Example 12-17.
Example 12-17. Import the organizing principle for the knowledge graph using neosemantics
CALL n10s.graphconfig.init({ handleVocabUris: "IGNORE", classLabel: "Concept", subclassOfRel: "broader"})
CALL n10s.skos.import.fetch("path-to-file-containing-organizing-principle","RDF/XML")- Run entity extraction on the contents of the articles and link the returned entities with the organizing principle. Notice the use of the
apoc.nlp.gcp.entities.streammethod in Example 12-18 that is in charge of calling the GCP Natural Language API used in this example.
Example 12-18. Call the GCP Natural Language API from Cypher to perform entity extraction
CALL apoc.periodic.iterate("MATCH (a:Article)WHERE a.processed IS NULLRETURN a", // (1)"CALL apoc.nlp.gcp.entities.stream([item IN $_batch | item.a], { // (2) nodeProperty: 'body', key: $key})YIELD node, valueSET node.processed = true // (3)WITH node, valueUNWIND value.entities AS entity // (4)WITH entity, nodeWHERE NOT (entity.metadata.wikipedia_url IS NULL)MATCH (c:Concept {altLabel: entity.metadata.wikipedia_url}) // (5)MERGE (node)-[rt:refers_to]->(c) SET rt.salience = entity.salience", // (6){batchMode: "BATCH_SINGLE", batchSize: 10, params: {key: $key}})YIELD batches, total, timeTaken, committedOperationsRETURN batches, total, timeTaken, committedOperations;A few comments on the previous code fragment:
- The logic is organized as an iterative producer-consumer structure
apoc.periodic.iterate. The first block"MATCH ..."streams batches of sizebatchSize: 10to the second block"CALL ..."that processes them. - In (1) you iterate over all articles that have not been processed yet. In (3) you flag articles as processed to make sure you do it only once per article.
- In (2) you invoke the GCP Natural Language API for each article in the batch. The method call includes two additional parameters: the name of the property containing the natural language text to be analyzed (
bodyin this example) and the API key required to use the service. - In (4) you iterate over the entities returned by the API, and you create nodes of type
Conceptfor each one of them in (5). - Finally, in (6) the
Articlenodes are linked to theConceptnodes through arefers_torelationship, weighted with the salience also returned by the API.
The result of this process is a graph quite similar to the one created in the previous section but now with the explicit semantics overlay added by the organizing principle:
- Entities become unambiguous and uniquely identifiable using a concept scheme. Such schemes can be public or private, use case or industry specific, departmental or enterprise wide.
- Entities become more interconnected in a meaningful and explainable way, offering new paths for exploration and analysis.
What kind of semantic exploitation can you carry out now? Well, now if you search for articles related to “NoSQL database management systems,” you would get results even though no single article explicitly mentions that set of terms.
Why is that? Because by bringing the organizing principle into the graph, you make it explicit that Neo4j is a graph database, and a graph database is a kind of NoSQL database (along with column stores, document databases, and key-value stores), as shown in Figure 12-7. This is what is often referred to as semantic search. You have managed to make your search independent of the ambiguous natural language text and base it on well-defined domain entities. In other words, you have effectively implemented the “things, not strings” principle.
Figure 12-7. Knowledge graphs are the strongest foundation for semantic search
In making the semantics (your knowledge about a domain) explicit, you are making them programmatically exploitable. A simple Cypher query like Example 12-19 captures the basic logic: You select the concept you are interested in, and the pattern (c:Concept)<-[:broader*0..]-(sc) recursively navigates the organizing principle to find any other concept that is a subconcept, at any level of depth. As a consequence, the query will return all the Article nodes directly or indirectly connected to the selected concept.
Example 12-19. A Cypher query finds articles based on concepts
MATCH (c:Concept)<-[:broader*0..]-(sc)<-[:refers_to]-(article:Article)WHERE c.prefLabel = "NoSQL database management system"RETURN article.title AS searchResultThis approach can be extended with multiple organizing principles. The articles in the example, just as products in a catalog can be classified according to multiple dimensions, effectively creating multiple complementary paths for both semantic search and similarity. This is an extremely powerful pattern and supercharges business information systems with search, in much the same way that knowledge graphs have supercharged Web search.
Here are some real-world scenarios where you can see these ideas in action.
In the field of health care, document annotation is applied to discharge summaries, clinical notes, scientific literature, and clinical trial protocols, among others. All of these documents are typically unstructured text. The results can be used to do advanced search and analysis of patient data, and it is also a step toward building a 360-degree view of the patient.
In news and media, document annotation can associate articles with searchable metadata describing key entities like persons, objects, locations, and events. Recommendations and personalization are the most obvious uses—“watch/read next…”—but not the only ones. When used on transcripts of audio or video media, annotation enables more sophisticated (and nonlinear) ways of consuming such media, like zooming in on specific moments and language in the timeline.
You have covered the case where the entity linkage is taken care of by the NER software. When that is not the case, some manual matching is required. Techniques for disambiguation include using textual analysis and graph analysis. One approach is annotating the concepts in the organizing principle with sets of keywords or even regular expressions to apply to the identifiers of the entities extracted by the NLP, as in Example 12-20.
Example 12-20. Annotate concepts with keywords and regular expressions
// keyword basedCREATE (c:Category { name: "Person", alts: ["Human","Pax", "Pers"]})
// regex based (inclusion/exclusion list)CREATE (c:Category { name: "COVID-19", inc: ["covid.*","corona.*"], excl: ["sars.*"]})One limitation of this approach is its strong reliance on the precision of such keywords or regexes. You would need to write some custom code to take care of the linkage, with logic similar to Example 12-21.
Example 12-21. Linking categories in Cypher
MATCH (e:Entity { name: $entityname })MATCH (c:Category)WHERE e.name IN c.altsWITH e, collect(c) AS candidate_catsWITH e, selection_logic(candidate_cats) AS selected_catMERGE (e)-[:references]->(selected_cat)The selection_logic function abstracts the problem of selecting the most plausible candidate in case there are multiple matches. It can be as simple as picking one random one, or assigning weights based on the relevance in the context, which could be computed using domain-specific heuristics or structural features like distance, centrality, or others.
Implementing Semantic Search in Rust
Section titled “Implementing Semantic Search in Rust”If you are using petgraph as an embedded knowledge graph in Rust, you can implement a lightweight semantic search pipeline by combining petgraph with Rust NLP and embedding libraries.
A common pattern is to use a local transformer model (via the rust-bert crate) to extract entities or generate dense vector embeddings for your documents. You can then store the structural ontology (like Figure 12-7) in petgraph.
Example 12-22. A conceptual pipeline for Semantic Search in Rust
use petgraph::graph::{DiGraph, NodeIndex};use petgraph::visit::Dfs;
#[derive(Debug, Clone)]pub enum NodeData { Concept { name: String }, Article { title: String },}
// Traverse the ontology in petgraph to find all related articlespub fn find_articles_by_concept( graph: &DiGraph<NodeData, ()>, start_concept_idx: NodeIndex) -> Vec<String> { let mut articles = Vec::new(); let mut dfs = Dfs::new(graph, start_concept_idx);
while let Some(nx) = dfs.next(graph) { if let NodeData::Article { title } = &graph[nx] { articles.push(title.clone()); } }
articles}By keeping the ontology and article relationships in petgraph, and executing the NLP entity extraction during your ingestion pipeline, your Rust application can offer blazing-fast, localized semantic search without requiring external database dependencies.
Case Study: NASA Lessons Learned
Semantic search knowledge graphs aren’t science fiction—they’re science fact. Dating all the way back to the Apollo moon missions in the 1960s and spanning more than half a century of collective knowledge, NASA’s “lessons learned” is a treasure trove of knowledge gained from positive experiences, such as successful missions and tests, and negative experiences, as in failures and mishaps.
NASA’s lessons learned information system (LLIS) contains hundreds of millions of documents, reports, and scientific research findings from multiple databases across the agency. Previously, it held less than 1% of the organization’s 20 million documents. With a total of 80,000 employees, the volume, variety, and velocity of data were taxing the system. NASA needed a better way for end users to access this information.
In the early 2000s, the LLIS was significantly underutilized because it was not easy to navigate or search. The biggest challenge was accessing the data, which was in silos strewn across groups, departments, programs, and products. Nothing connected or even cross-referenced the data. Keyword search queries across all 20 million documents took a long time to run. Search results returned 1,100 documents. The user would then need to read those articles (or at least scan them) to get to an answer.
But there was hope. There is a great deal of metadata associated within the lessons learned, so NASA was able correlate the topics (by extracting entities) based on their self-assigned categories. They could see each lesson with its topic as well as correlations between topics, so they could also see how topics correlated to one another. This allowed users to look at trends, which can potentially help NASA engineers prevent disastrous outcomes.
Fast forward to today, and LLIS at NASA is now a rich knowledge graph. Search is faster and provides fewer—but much more relevant—results. The knowledge graph plays a fundamental role in two main ways.
First, it gathers data from various siloed sources (as per Chapter 5). It then links the data together via entities using the techniques in this chapter. The lessons learned database has already generated significant value. One NASA engineer said, “This has saved us at least a year and over $2M in research and development towards our Mission to Mars planning.” If your semantic search knowledge graphs are as good, who knows how far they’ll take you?
Summary
Section titled “Summary”The ability to search for concepts rather than specifying index keys is revolutionary. Using a semantic search knowledge graph, this becomes possible. Not only does your organization keep more of its knowledge, but accessing that knowledge becomes straightforward through the knowledge graph.
From semantic search, you can go one level further and try to understand natural language. In the next chapter, you’ll see how search and NLP go hand in hand, using real-world examples to demonstrate.