Talking to Your Knowledge Graph
local graph
Chapter 13 — Talking to Your Knowledge Graph
Section titled “Chapter 13 — Talking to Your Knowledge Graph”In the previous chapter, you saw NLP applied to the construction of knowledge graphs to support semantic search over collections of things (articles, products, documents, and so forth). This relied on an NLP task called entity extraction, or NER. But NER is only one of the ways in which NLP can interact with knowledge graphs, out of three broad categories:
- Where knowledge graphs are populated with entities, facts and knowledge come from applying NLP techniques to natural language text. This includes what you learned in Chapter 12 as well as the cases where NLP is used for fact extraction to build question-answering knowledge graphs. This category is natural language as input to a knowledge graph.
- You will see in this chapter how natural language can also be generated from knowledge graphs. This can be used to produce a conversational answer to a query or for automated report generation, as some examples. This category is natural language as output.
- Somewhere in between, knowledge graphs can be a tool providing structured context for NLP tasks, either at the lexical or at the conceptual level (or both).
Figure 13-1 depicts the three categories.
Figure 13-1. Types of interaction between natural language and knowledge graphs
This chapter is split into three parts. In the first part, you will learn how NER can be complemented with fact extraction to build a knowledge graph for answering questions as opposed to document search and recommendation. The second part explores techniques for implementing conversational interfaces to interact with the knowledge graph. This includes both processing natural language questions and translating them into structured queries on the graph, as well as generating text from the graph to produce the answers. The last section focuses on knowledge graphs for lexical databases where you need to build a custom entity extractor which has specialized domain knowledge. You will learn how a public lexical database (like WordNet) can be used to provide a detailed analysis of the use of such specialized knowledge graphs and the implementation of semantic similarity metrics in them.
Question Answering: Natural Language as a Source of Facts for a Knowledge Graph
Section titled “Question Answering: Natural Language as a Source of Facts for a Knowledge Graph”The techniques described in the previous chapter were document centric. You applied NER and entity disambiguation to the items (products, articles, documents…) in a collection to annotate them and build a knowledge graph capable of doing effective semantic search over large sets of documents or computing semantic similarity between documents to drive recommendation and penalization.
In this section, you will explore the case when documents are just a source of facts that get interconnected in a knowledge graph with the objective of answering domain questions rather than carrying out sophisticated tasks on the documents they are extracted from. In this type of scenario, you query the knowledge graph expecting an answer, not a list of documents where you will find that answer.
Note that this is not incompatible with keeping a reference to the source documents for provenance and trust purposes, but the ultimate objective is the creation of a knowledge graph that will not answer the question “Which documents talk about Tesla?” but rather “Who is the CEO of Tesla?” or “Where is Tesla’s headquarters?”
The nature and complexity of the NLP used will vary and with it the richness of the graph created from the unstructured data. The role of the NLP moves from entity extraction to fact extraction. This effectively means that you will want to extract statements from the natural language text that will then be modeled in the graph as either node properties or relationships connecting nodes.
To show this in action, the example will use yet another NLP package: Diffbot (https://www.diffbot.com). Diffbot’s Natural Language API offers fact extraction in addition to entity extraction. Example 13-1 shows some sample code that takes the first sentence in one of the articles and extracts facts from it by invoking the Diffbot Natural Language API.
Example 13-1. Using Diffbot’s Natural Language API to extract facts from text
import jsonimport requests
payload = { "content": "Pichette is a partner at Inovia Capital and chair of " \ "commerce platform Lightspeed", "lang": "en"}res = requests.post("https://{}/v1/?fields={}&token={}".format( HOST, "entities,facts", TOKEN), json=payload)
for ent in res.json()["entities"]: print(ent) # write to graph
for fact in res.json()["facts"]: print(fact) # write to graphThe extracted facts are structured as entity-property-value triplets. The real output is a rich JSON structure like the one shown in Example 13-2 that includes unique identifiers, cross references to public knowledge bases like Wikidata, and additional attributes like salience, confidence, sentiments, and others.
Example 13-2. Raw facts extracted with the Diffbot Natural Language API
{ "sentiment": -0.32881057, "entities": [ { "name": "Patrick Pichette", "confidence": 0.81, "salience": 0.64345313, "sentiment": 0.0, "isCustom": false } ], "facts": [ { "humanReadable": "[Patrick Pichette] employee or member of [Innovia Capital]", "entity": { "name": "Patrick Pichette", "diffbotUri": "https://diffbot.com/entity/EYwbLa__MNVGtPMryqqCCEA", "confidence": 0.9999268, "allUris": ["http://www.wikidata.org/entity/Q3369779"], "allTypes": [ { "name": "person", "diffbotUri": "https://diffbot.com/entity/E4aFoJie0MN6dcs_yDRFwXQ", "dbpediaUri": "http://dbpedia.org/ontology/Person" } ], "isCustom": false, "entityIndex": 5 }, "property": { "name": "employee or member of", "diffbotUri": "https://docs.diffbot.com/ontology#Person.memberOf" }, "value": { "name": "Innovia Capital", "confidence": 0.9989188, "allUris": [], "allTypes": [ { "name": "organization", "diffbotUri": "https://diffbot.com/entity/EGTSOJhZ0NnqIjbJgQ8pyLg" } ] }, "confidence": 0.9498123, "evidence": [ { "passage": "Pichette is a partner at Inovia Capital", "entityMentions": [ { "text": "Pichette", "beginOffset": 111, "endOffset": 113, "isPronoun": false, "confidence": 0.9985091 } ], "valueMentions": [ { "text": "Innovia Capital", "beginOffset": 119, "endOffset": 132, "confidence": 0.9989188 } ] } ] } ]}A visual and more intuitive view of the same output is presented in Figure 13-2.
| Entity | Property | Value | Qualifiers |
|---|---|---|---|
| Patrick Pichette | employee or member of (0.91) | Inovia Capital | is current |
| Patrick Pichette | skilled at (0.54) | commerce | |
| Patrick Pichette | employee or member of (0.95) | Lightspeed | is current |
| Lightspeed | industry (0.65) | commerce |
Figure 13-2. Diffbot Natural Language API extracts facts from text
That output can be directly consumed to populate the knowledge graph, as shown in Example 13-3.
Example 13-3. Importing facts from Diffbot into your knowledge graph
# code incomplete...entity_list = res.json()["entities"]fact_list = res.json()["facts"]
# call write transaction with params entities and facts and Cypher below
cypher = """UNWIND $facts AS factMERGE (source:Entity { id: fact.entity.diffbotUri })MERGE (target:Entity { id: fact.value.diffbotUri })WITH source, target, factCALL apoc.create.relationship(source, fact.property.name, {}, target)// add salience etc"""A knowledge graph of these characteristics can then be queried (see Example 13-4) to answer domain questions like “Which individuals are directly related to Inovia Capital and what’s the nature of their relationship?”
Example 13-4. A Cypher query shows who is related to Inovia Capital
MATCH (:Organization { name : "Inovia Capital"})-[rel]-(p:Person)RETURN p.name AS person, type(rel) AS rel_typeRunning the Cypher query in Example 13-4 produces the expected results shown in Example 13-5.
Example 13-5. Results of a Cypher query showing who is related to Inovia Capital
| person | rel_type |
|---|---|
| “Patrick Pichette” | “EMPLOYEE_OR_MEMBER_OF” |
The challenge with this approach is the harmonization of relationships. To avoid undesired proliferation of relationships between entities, fact extraction tools need additional input about the types of relationships that are relevant and how to identify and disambiguate them.
Using Natural Language Query with a Knowledge Graph
Section titled “Using Natural Language Query with a Knowledge Graph”You have seen how information rich a knowledge graph can be, and you have also seen that you can get value from it through both visual exploration with tools like Bloom and programmatic access with Cypher. While Bloom is more universal and only requires a basic understanding of the domain, Cypher is only really accessible to technical specialists. One way to widen the spectrum of potential users getting value from a knowledge graph is by enabling natural-language-based interfaces. You are no doubt used to interacting with personal assistants like Siri or Alexa using your voice or having conversations with chatbots when contacting the customer support of any of your service providers. While you are aware that you are exploring a knowledge base, being able to articulate your questions in natural language lowers the barrier for accessing the content. In the world of knowledge graphs, conversational interactions require the translation of natural language into a structured query to the graph.
In this section, you will see a motivating example to guide you through the process. The example shows how to implement a basic natural language interface for Neo4j’s movie database. The NLP library used in this case will be spaCy (https://spacy.io), using its rule-based matching capability.
If you are familiar with regular expressions, spaCy’s rule-based matcher engines take this approach to the next level. In addition to finding words and phrases, they give you access to the tokens within the document and their relationships. This means you can easily access and analyze the surrounding tokens, combine them, process them to make sense of the meaning of the natural language question, and ultimately be able to translate it into a structured query in Cypher.
Before getting into the details, you can initialize the knowledge graph with the movies dataset with a simple instruction on the Neo4j Browser, :play movies, and then click through to have the nodes and relationships created. The resulting graph contains two types of entities, Person and Movie, connected through relationships of type ACTED_IN, DIRECTED, PRODUCED, WROTE, and REVIEWED. Figure 13-3 shows a small excerpt of the resulting graph.
Figure 13-3. Excerpt of the movie knowledge graph representing the movie A Few Good Men
The sentence types that this pattern will capture are of the form “Who directed The Da Vinci Code?” or “Do you know who wrote A Few Good Men?” You can get all the details in the spaCy documentation (https://oreil.ly/Tvivz), but you are defining a pattern with four components (tokens):
- The word
whodescribed in its lowercase form. This means that if the input uses any case variant of it (Who, WHO, …), the pattern will still work. - A verb—that is, what the part of speech configuration specifies
"POS": "VERB"—having as lemma any of the ones in the list:direct,produce,write,review. A lemma is the canonical form of a set of words. In this case,directwould be the lemma fordirectsordirected. - A word, any alphanumeric word (
IS_ASCII), with one important modifier: it can appear one or more times. That is what the optionality modifier'OP': '+'specifies. - The pattern ends with an optional punctuation sign. This would correspond to the question mark when used. It has been made optional (again with the optionality modifier
'OP': '?') for the cases where the request is formulated in an assertive way rather than as a question: “Tell me who wrote X.”
The pattern is added to the Matcher in (1), and when the sentence do you know who wrote a few good men? is passed to the nlp method in (2), it does match the pattern and will therefore be included in the results in (3). The result includes all the information you need to transform the detected meaning into a valid Cypher query. All you need is a way to map the different verbs that the second token in the pattern can match to the relevant schema elements in your graph model.
A simple way to do this is to build a dictionary with the correspondences. In this pattern, the verbs correspond to relationships in the graph so the code in Example 13-7 should as well.
Example 13-7. A Matcher capturing simple questions about movies (part 2)
# map tokens to graph schema elementsq1_verb_to_rel = {"direct" : "DIRECTED", "produce" : "PRODUCED", "write" : "WROTE", "review" : "REVIEWED"}
max_match = result[-1]verb = max_match[1].lemma_ # (1)title = ' '.join([tk.text for tk in max_match[2:] if tk.pos_ != 'PUNCT']) # (2)query_as_cypher = "MATCH (p:Person)-[:{rel_type}]->(m:Movie) " \ "WHERE toLower(m.title) CONTAINS '{movie_title}' " \ "WITH collect(p.name) AS answer_as_list " \ "RETURN CASE WHEN size(answer_as_list) > 0 THEN " \ " substring(reduce(result='', x in answer_as_list | result + ', ' + x),2) " \ " ELSE \"I cannot answer your question about \" " \ "'{movie_title}' \" end AS answer " \ .format(rel_type=q1_verb_to_rel[verb], movie_title=title.lower()) # (3)
print(query_as_cypher)You can extract the relevant tokens from the Span (a Span is a sequence of tokens in spaCy terminology). In (1) the verb is extracted, followed by (2) where the collection of words that represent the movie title in the sentence are also extracted. With the results of (1) and (2), it’s easy to build a query that encodes the semantics of the natural language received as input.
Ignoring the last four lines that take care of the formatting of the output, the query synthesized by this process is the one you would expect from visually inspecting the graph and is shown in Example 13-8.
Example 13-8. The Cypher query generated from a natural language fragment
MATCH (p:Person)-[:WROTE]->(m:Movie)WHERE toLower(m.title) CONTAINS 'a few good men'WITH collect(p.name) AS answer_as_listRETURN CASE WHEN size(answer_as_list) > 0 THEN substring(reduce(result='', x in answer_as_list | result + ', ' + x),2) ELSE "I cannot answer your question about 'a few good men' "END AS answerYou may be thinking that this is a quite scripted approach because you have to be explicit about all the patterns that you want your Matcher to be aware of. That is correct to some extent, but in the next section you will see how to fully automate this by annotating the organizing principle in your knowledge graph. To understand how this is possible, remember that the graph is a self-describing data structure. You can ask the graph the types of entities, properties, and relationships that it’s aware of just by calling the db.schema.* procedures. Some simple annotation on the common natural language terms for the elements in the schema is all that’s needed to dynamically create a rich natural language interface and have it evolve as the knowledge graph evolves.
To complete this section, Example 13-9 shows the entire code of a rule-based conversational interface with multiple different patterns interacting with a Neo4j graph database.
Example 13-9. A conversational interface
import spacyfrom spacy.matcher import Matcherfrom neo4j import GraphDatabase, basic_auth
driver = GraphDatabase.driver( "bolt://localhost:7687", auth=basic_auth("neo4j", "neo"))session = driver.session(database="neo4j") # 1
def query_db(session, cypher): # 2 results = session.read_transaction( lambda tx: tx.run(cypher).data()) return results[0]["answer"]
nlp = spacy.load('en_core_web_sm')
matcher = Matcher(vocab=nlp.vocab)
q1_pattern = [{"LOWER": "who"}, {"LEMMA": {"IN": ["direct", "produce", "write", "review"]}, "POS": "VERB"}, {'IS_ASCII': True, 'OP': '+'}, {'IS_PUNCT': True, "OP": "?"}]
q1_verb_to_rel = {"direct" : "DIRECTED", "produce" : "PRODUCED", "write" : "WROTE", "review" : "REVIEWED"}matcher.add("q_1", [q1_pattern]) # 3
q2_pattern = [{"LOWER": "when"}, {"LEMMA": "be"}, {'IS_ASCII': True, 'OP': '+'}, {"LEMMA": {"IN": ["release","premiere"]}, "POS": "VERB", "OP": "?" }, {"LEMMA": "out", "OP": "?" }, {'IS_PUNCT': True, "OP": "?"}]
q2_word_to_prop = {"release" : "released", "premiere" : "released", "out" : "released"}matcher.add("q_2", [q2_pattern]) # 4
q3_pattern = [{"LOWER": "who"}, {"LEMMA": {"IN": ["act", "perform", "appear", "be"]}, "POS": {"IN": ["VERB", "AUX"]}}, {"LEMMA": "in"}, {'IS_ASCII': True, 'OP': '+'}, {'IS_PUNCT': True, "OP": "?"}]
matcher.add("q_3", [q3_pattern]) # 5
def process_question(question): # 6 doc = nlp(question)
result = matcher(doc, as_spans=True)
if (len(result) > 0): max_match = result[-1] pattern_detected = nlp.vocab[max_match.label].text # 7 if (pattern_detected == 'q_1'): verb = max_match[1].lemma_ title = ' '.join([tk.text for tk in max_match[2:] if tk.pos_ != 'PUNCT']) query_as_cypher = "MATCH (p:Person)-[:{rel_type}]->(m:Movie) " \ "WHERE toLower(m.title) CONTAINS '{movie_title}' " \ "WITH collect(p.name) AS answer_as_list " \ "RETURN CASE WHEN size(answer_as_list) > 0 THEN " \ " substring(reduce(result='', x in answer_as_list" \ " | result + ', ' + x),2) " \ " ELSE \"I cannot answer your question about \" " \ "'{movie_title}' \" end AS answer " \ .format(rel_type=q1_verb_to_rel[verb], movie_title=title.lower())
elif (pattern_detected == 'q_2'): word_pos = -2 if max_match[-1].is_punct else -1 word = max_match[word_pos].lemma_ title = ' '.join([tk.text for tk in max_match[2:word_pos]]) query_as_cypher = "MATCH (m:Movie) " \ "WHERE toLower(m.title) CONTAINS '{movie_title}' " \ "WITH collect(m.{movie_prop}) AS answer_as_list " \ "RETURN CASE WHEN size(answer_as_list) > 0 THEN " \ " substring(reduce(result='', x in answer_as_list" \ " | result + ', ' + toString(x)),2) " \ " ELSE \"I cannot answer your question about \" " \ "'{movie_title}' \" end AS answer " \ .format(movie_prop=q2_word_to_prop[word], movie_title=title.lower())
elif (pattern_detected == 'q_3'): title = ' '.join([tk.text for tk in max_match[3:-1]]) query_as_cypher = "MATCH (p:Person)-[:ACTED_IN]->(m:Movie) " \ "WHERE toLower(m.title) CONTAINS '{movie_title}' " \ "WITH collect(p.name) AS answer_as_list " \ "RETURN CASE WHEN size(answer_as_list) > 0 THEN" \ " substring(reduce(result='', x in answer_as_list |" \ " result + ', ' + x),2) " \ " ELSE \"I cannot answer your question about \" " \ "'{movie_title}' \" end AS answer " \ .format(movie_title=title.lower())
print("Q:", question) print("A:", query_db(session, query_as_cypher)) print("Explain:", query_as_cypher[:90], "...\n")
questions = ["could you tell me who reviewed the Da Vinci code?","who directed unforgiven ?","do you happen to know who appears in Jerry Maguire?","Who acts in Apollo 13?","tell me when was the birdcage released","do you know who produced the matrix reloaded?","do you remember who was in cloud atlas","name the person who wrote When Harry Met Sally","when was top gun out?"] # 8
for question in questions: process_question(question) # 9
driver.close()Example 13-9 starts by initializing a driver and a session to talk to the knowledge graph in (1). In (2) a function query_db is defined to use the session created in (1) and run a read query. It takes only one parameter, the Cypher query itself, and returns a string with the result of running the query on the graph. In (3), (4), and (5) you register each pattern with a unique identifier for the type of queries that it describes. This will be useful in (7) to identify which of the patterns has been detected in the text and generate the right Cypher query by following the relevant branch in the if structure. The whole processing of the text has been bundled in a function called process_question defined in (6), which takes the natural language question and prints out three values: the original question in natural language, the answer to the question returned from running the Cypher translation against the movies knowledge graph, and the Cypher query itself as an explanation.
A few natural language sentences are defined in (8) and used as a test in (9), producing the results shown in Example 13-10. (Note that the queries have been truncated for brevity, but the final fragment is very similar to the one generated in Example 13-8 and can also be gleaned from the source code in Example 13-9.)
Example 13-10. Results of processing natural language questions on the movie database
Q: could you tell me who reviewed the Da Vinci code?A: Jessica Thompson, James ThompsonExplain: MATCH (p:Person)-[:REVIEWED]->(m:Movie) WHERE toLower(m.title) CONTAINS 'the da vinci code ...
Q: who directed unforgiven ?A: Clint EastwoodExplain: MATCH (p:Person)-[:DIRECTED]->(m:Movie) WHERE toLower(m.title) CONTAINS 'unforgiven' WITH ...
Q: do you happen to know who appears in Jerry Maguire?A: Bonnie Hunt, Jay Mohr, Cuba Gooding Jr., Jonathan Lipnicki, ...Explain: MATCH (p:Person)-[:ACTED_IN]->(m:Movie) WHERE toLower(m.title) CONTAINS 'jerry maguire' wi ...
Q: Who acts in Apollo 13?A: Tom Hanks, Ed Harris, Gary Sinise, Kevin Bacon, Bill PaxtonExplain: MATCH (p:Person)-[:ACTED_IN]->(m:Movie) WHERE toLower(m.title) CONTAINS 'apollo 13' WITH c ...
Q: tell me when was the birdcage releasedA: 1996Explain: MATCH (m:Movie) WHERE toLower(m.title) CONTAINS 'the birdcage' WITH collect(m.released) AS ...
Q: do you know who produced the matrix reloaded?A: Joel SilverExplain: MATCH (p:Person)-[:PRODUCED]->(m:Movie) WHERE toLower(m.title) CONTAINS 'the matrix reload ...
Q: do you remember who was in cloud atlasA: Tom Hanks, Jim Broadbent, Halle Berry, Hugo WeavingExplain: MATCH (p:Person)-[:ACTED_IN]->(m:Movie) WHERE toLower(m.title) CONTAINS 'cloud a ...
Q: name the person who wrote When Harry Met SallyA: Nora EphronExplain: MATCH (p:Person)-[:WROTE]->(m:Movie) WHERE toLower(m.title) CONTAINS 'when harry met sally ...
Q: when was top gun out?A: 1986Explain: MATCH (m:Movie) WHERE toLower(m.title) CONTAINS 'top gun' WITH collect(m.release...Natural Language Generation from Knowledge Graphs
Section titled “Natural Language Generation from Knowledge Graphs”Often there’s a need to generate natural language out of a knowledge graph. Examples of this can be generating a report in natural language from an investigative exercise in a graph (such as the Panama Papers investigation (https://oreil.ly/Yq83_) or just the results of a query as the output of a conversational interface.
In this context, the self-describing nature of graph data gives a substantial advantage. Start with the basic (but still largely valid) modeling approach that transforms nouns in nodes in the graph and verbs in relationships. A good example is the already famous sentence “Dan loves Ann.” When modeled as a graph, it becomes two nodes representing the two nouns Dan and Ann and one relationship connecting Dan to Ann representing the verb to love.
If you invert this logic and generalize it, you can produce a simple protosentence of the form “subject-predicate-object” by just concatenating the words identifying any pair of nodes in a graph, connected by a word identifying the relationship. An example of a minimal subgraph extracted from the Panama Papers database can be created with the script in Example 13-11.
Example 13-11. A simple fragment from the Panama Papers dataset
MERGE (x:Entity { name: "Euroyacht Limited" , jurisdiction: "BM" })MERGE (y:Entity { name: "TUC LIMITED", jurisdiction: "MLT", incorporation_date: date("2013-10-07")})MERGE (z:Entity {name: "GLOBAL TUITION & EDUCATION INSURANCE CORPORATION", jurisdiction: "BRB", incorporation_date: date("1998-04-03") })MERGE (x)-[:OFFICER_OF]->(y)MERGE (x)-[:OFFICER_OF]->(z)Now you can write a completely generic query capturing any pair of nodes connected by a relationship (pattern (x)-[r]->(y)) and returning a string built by concatenating the three elements to form the basic sentence shown in Example 13-12.
Example 13-12. A completely generic query producing basic sentences from the graph structure and data
MATCH (x)-[r]->(y)RETURN x.name + " " + toLower(replace(type(r),"_"," ")) + " " + y.name AS sentenceNotice that the query contains some basic formatting like adding a couple of whitespaces to separate words and replacing the underscores in names with whitespaces to make it even more natural. Nothing very sophisticated for this initial example. The query produces the results shown in Example 13-13, which are surprisingly close to correct English.
Example 13-13. Result of running a completely generic query producing a basic English sentence from the graph structure and data
| sentence |
|---|
| “Euroyacht Limited officer of GLOBAL TUITION & EDUCATION INSURANCE CORPORATION” |
| “Euroyacht Limited officer of TUC LIMITED” |
Given the fact that the query is totally generic in the sense that it does not contain any schema-specific elements, it would be valid for any graph. Taking this same query and running it on the movie database shipped with Neo4j (just run the :play movies command) would produce sentences like “Keanu Reeves acted in Johnny Mnemonic.”
It’s quite good value for two lines of code. But it does not stop here. The same concept can be applied to the properties of a node too, as shown in Example 13-14.
Example 13-14. Another completely generic query producing basic sentences from the graph structure and data
MATCH (n:Entity) UNWIND keys(n) AS propertyRETURN n.name + "'s " + replace(property,"_"," ") + " is " + toString(n[property]) AS sentenceThis property-oriented query produces results shown in Example 13-15 that are once again decent English fragments.
Example 13-15. Result of running a completely generic query producing a basic sentence from the graph structure and data
| sentence |
|---|
| “Euroyacht Limited’s jurisdiction is BM” |
| “TUC LIMITED’s jurisdiction is MLT” |
| “TUC LIMITED’s incorporation date is 2013-10-07” |
| “GLOBAL TUITION & EDUCATION INSURANCE CORPORATION’s jurisdiction is BRB” |
| “GLOBAL TUITION & EDUCATION INSURANCE CORPORATION’s incorporation date is 1998-04-03” |
This is a great starting point that reflects practically how the structure captured by a knowledge graph can be directly read and used to generate natural language. This is empiric confirmation that graphs capture the understanding of a domain similar to humans. It’s quite straightforward to read the information from a knowledge graph and express it in natural language.
But there are a couple of points that have been temporarily ignored in the previous examples and that are important in this process. If you paid close attention, you might have noticed that the previous queries were not completely generic; they did actually contain one schema element: the property name. Generating subject-predicate-object sentences requires having a way to name things (nodes). The previous queries assumed that there would always be a name property, which is not necessarily the case. For a generally valid solution, a way of referring to nodes would be required.
Another thing to keep in mind is that, depending on how relationships and properties are named (the graph’s schema), the resulting sentences will be more or less readable. Think of the sentence that would result from a relationship called sub_109. A generally valid solution will want to detach itself from the actual schema element names. While it can be practical to have a relationship named sub_109 to be able to write compact Cypher queries, a natural-language-oriented annotation of the property would be required to make the two independent of each other.
Finally, the previous queries navigated outgoing relationships (from source to target). But sometimes exploring incoming relationships is required. Linguistically, that’s a challenge since Person - ACTED_IN - Movie or Entity - HAS_JURISDICTION - Jurisdiction only reads correctly one way around. You solve this problem by providing additional annotation for relationships for navigation in both directions containing the reciprocal natural language: MOVIE - FEATURED - Actor for example. But a more general approach can be achieved through annotating the knowledge graph’s ontology, which is explored next.
Annotating the Knowledge Graph’s Organizing Principle to Drive Natural Language Generation
Section titled “Annotating the Knowledge Graph’s Organizing Principle to Drive Natural Language Generation”This section presents an automated approach for generating natural language from a property graph by creating and annotating an ontology with information that a general-purpose natural language generator uses to produce high-quality natural language from the data. It’s assumed that such ontology will be stored along with the instance data in such a way that the natural language engine will have access to both, but it’s important to understand that this approach could be generalized to follow alternative architectures: the ontology could be read directly from an external repository, stored in a separate graph in a fabric configuration, and so on.
The starting point is to create and store the ontology of the knowledge graph. An ontology can be formalized using W3C standards like RDF Schema or OWL and then imported into Neo4j using the neosemantics plugin or, alternatively, created as a set of nodes and relationships directly in Neo4j.
The ontology contains descriptions for the types of entities that will be described using natural language. This declarative description of the schema can also be seen as the configuration for a general-purpose natural language generation engine to work.
The examples use the movies database that contains nodes of type Person and Movie. The first requirement is to identify for each node type the property that will be used to refer to the node. In the case of nodes of type Person, it will be the property name, and for nodes of type Movie, it will be the property title. This can be formally described using OWL, as shown in Example 13-16.
Example 13-16. Ontology annotated with information on entity names
@prefix owl: <http://www.w3.org/2002/07/owl#> .@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .@prefix talk: <http://www.neo4j.org/2022/07/talkable#> .@prefix mv: <http://www.neo4j.org/sch/movies#> .
mv:Movie rdf:type owl:Class ; talk:name "title" ; rdfs:label "Movie" .
mv:Person rdf:type owl:Class ; talk:name "name" ; rdfs:label "Person" .This can be generated either manually or with any ontology modeling tool and then imported into Neo4j using the neosemantics plugin in one line, as shown in Example 13-17.
Example 13-17. Code to import an ontology into Neo4j
CALL n10s.onto.import.fetch("file containing the onto","Turtle")If compliance with W3C standards is important to your project and/or reuse of existing ontologies, then the previous two steps will be extremely useful. If that does not apply to you, the same can be achieved with Cypher, as shown in Example 13-18.
Example 13-18. Creating an organizing principle with plain Cypher
CREATE (:Class { name:"title", label:"Movie" })These annotated class definitions help the engine determine how to refer to nodes when producing a natural language sentence. When talking about a Movie, you will use its title, and when talking about a Person, you will use its name property. The next thing is to describe and annotate relationships. Example 13-19 shows how.
Example 13-19. Ontology annotated with information on relationships
@prefix owl: <http://www.w3.org/2002/07/owl#> .@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .@prefix talk: <http://www.neo4j.org/2022/07/talkable#> .@prefix mv: <http://www.neo4j.org/sch/movies#> .
mv:ACTED_IN rdf:type owl:ObjectProperty ; rdfs:domain mv:Person ; rdfs:range mv:Movie ; talk:direct "acted in"@default , "is in the cast of"@long , "worked in"@short ; talk:inverse "has $o in it"@default , "includes"@short , "includes $o in its cast"@long ; rdfs:label "ACTED_IN" .
mv:WROTE rdf:type owl:ObjectProperty ; rdfs:domain mv:Person ; rdfs:range mv:Movie ; talk:direct "is the author of"@default , "wrote"@short , "wrote the script of"@long ; talk:inverse "is authored by"@default , "is written by"@long , "is by"@short ; rdfs:label "WROTE" .For each of the relationships in the knowledge graph that you’d like to express in natural language, you need to provide the source and target in the form of domain and range and annotate them with both a direct and inverse way of navigating it. What that means is that when traversing the relationship in the natural direction—in the case of ACTED_IN, that would be from the Person to the Movie—use one of the direct expressions: “person X is in the cast of movie Y.” But when navigating the relationship in the inverse way (from Movie to Person), take one of the inverse expressions: “movie Y includes person X.” Multiple versions of the natural language to be generated from the relationship are provided. In the example, there is a long and a short form, but you could have a formal and a casual one chosen, depending on context. Finally, parameters are used to add more flexibility to the natural language generated (noted with the $ sign). Sometimes the basic pattern subject-predicate-object is too limiting to generate richer expressions. When you want to describe the ACTED_IN connection between Keanu Reeves and the movie The Matrix in natural language, for example, you express it with a sentence like “The Matrix has Keanu Reeves in it.” The object (Keanu Reeves) is embedded in the sentence rather than appended at the end.
Finally, a similar definition for node properties is provided, as shown in Example 13-20.
Example 13-20. Ontology annotated with information on node properties
@prefix owl: <http://www.w3.org/2002/07/owl#> .@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .@prefix talk: <http://www.neo4j.org/2022/07/talkable#> .@prefix mv: <http://www.neo4j.org/sch/movies#> .
mv:born rdf:type owl:DatatypeProperty ; rdfs:domain mv:Person ; talk:direct "The birth year of $s was"@long , "spawned in"@short , "was born in"@default ; rdfs:label "born" .
mv:released rdf:type owl:DatatypeProperty ; rdfs:domain mv:Movie ; talk:direct "premiered in"@short , "The release year of $s was"@long , "was released in"@default ; rdfs:label "released" .
mv:tagline rdf:type owl:DatatypeProperty ; rdfs:domain mv:Movie ; talk:direct "'s tagline goes: '$o'"@default , "'s tagline is"@short , "the tagline for $s was"@long ; rdfs:label "tagline" .With this type of description stored in the graph along with the data, the Cypher expression in Example 13-21 can dynamically generate a natural language description of any given node.
Example 13-21. A Cypher natural language generating engine driven by the ontology
MATCH (n)-[r]-(o) WHERE id(n) = $entity_idMATCH (cn:Class)<-[:domain|range]-(op:ObjectProperty)-[:domain|range]->(co:Class)WHERE type(r) IN op.labelAND (op.direct IS NOT NULL OR op.inverse IS NOT NULL)AND [x IN labels(n) WHERE x <> "Resource"][0] IN cn.labelAND [x IN labels(o) WHERE x <> "Resource"][0] IN co.labelWITH n[cn.name[0]] AS subj, n10s.rdf.getLangValue("default", op[CASE WHEN startNode(r) = n THEN "direct" ELSE "inverse" END]) AS pred, substring(reduce(res="", x IN collect(o[co.name[0]]) | res + "," + x),1) AS objWITH CASE WHEN pred CONTAINS '$s' THEN '' ELSE subj END AS subj, replace(replace(pred,'$o',obj),'$s',subj) AS pred, CASE WHEN pred CONTAINS '$o' THEN '' ELSE obj END AS objRETURN subj + " " + pred + " " + obj AS sentenceExample 13-21 can produce competent sentences like those in Example 13-22.
Example 13-22. A Cypher natural language generating engine driven by the ontology
| sentence |
|---|
| “Lilly Wachowski wrote V for Vendetta,Speed Racer” |
| “Laurence Fishburne worked in The Matrix Revolutions,The Matrix Reloaded,The Matrix” |
| “Hugo Weaving worked in Cloud Atlas,V for Vendetta,The Matrix Revolutions,The Matrix Reloaded,The Matrix” |
| “Lana Wachowski wrote V for Vendetta,Speed Racer” |
| “Emil Eifrem worked in The Matrix” |
This approach offers a pure Cypher solution to the generation of natural language from a knowledge graph by using an ontology as a configuration artifact. For any given X, it returns a natural language description of “all the knowledge graph knows about X”. While this can be useful for generating documentation and similar use cases, it’s still quite limited.
More sophisticated approaches can include the use of lexical databases like WordNet (https://oreil.ly/dzGj-) or ML elements that can learn from common expressions and eventually reconfigure themselves instead of requiring manual sentence pattern definitions.
Example 13-23 shows a small fragment of a real-world example using the open source bot framework Rasa (https://rasa.com). Rasa includes “knowledge base actions” to leverage information from external databases and can be used to interact with a knowledge graph built on Neo4j.
Example 13-23. Connecting the Rasa open source bot framework to a Neo4j knowledge graph
from rasa_sdk.knowledge_base.storage import KnowledgeBasefrom rasa_sdk.knowledge_base.actions import ActionQueryKnowledgeBase
class MyKnowledgeBaseAction(ActionQueryKnowledgeBase): def __init__(self): knowledge_base = KnowledgeBase("ref to neo4j") super().__init__(knowledge_base)Working with Lexical Databases
Section titled “Working with Lexical Databases”WordNet (https://oreil.ly/saBy2) is a lexical database of English. Nouns, verbs, adjectives, and adverbs are grouped into sets of cognitive synonyms (called synsets), each expressing a distinct concept. Synsets are interlinked by means of conceptual-semantic and lexical relations. The result is a network of elements that can be stored naturally in a graph.
Before exploring some of the possibilities for analyzing the WordNet database as a graph, it’s worth understanding how to construct that graph. Use a public version of WordNet published by the Global WordNet Association (https://oreil.ly/Iqc-V). The latest release can be found in the WordNet GitHub repository (https://oreil.ly/pHPKh).
One of the formats available for WordNet is RDF. This simplifies things significantly because you can automate importing RDF into Neo4j, as shown in Example 13-24.
Example 13-24. Importing RDF into your knowledge graph using Cypher
CREATE CONSTRAINT n10s_unique_uri ON (r:Resource) ASSERT r.uri IS UNIQUE;
CALL n10s.graphconfig.init({handleVocabUris : "IGNORE"});
CALL n10s.rdf.import.fetch(".../english-wordnet-2021.ttl.gz","Turtle");Figure 13-4 shows a fragment of the structure (schema) of the graph, whose form is Lexical Entry–Lexical Sense–Lexical Concept.
Figure 13-4. The main graph pattern in the WordNet knowledge graph
An explicit and detailed graph representation of a lexical database like WordNet has many different uses, but most importantly, it gives control over its content and makes it possible to adapt and extend it for specific uses. But first, it’s interesting to try some basic queries over the graph that return meanings of words or reveal the nature of certain words, such as their precision or their ambiguity.
WordNet can be used to get all possible meanings of a word or a set of words. Most queries in this analysis will be based on a traversal of the main graph pattern Form–Lexical Entry–Lexical Sense–Lexical Concept, shown in Figure 13-4.
The Cypher query shown in Example 13-25 returns all the meanings for the word clear.
Example 13-25. A Cypher query that returns all the meanings for the word clear
MATCH (lemma:Form)<-[:canonicalForm]-(le:LexicalEntry)-[:sense]->()-[:isLexicalizedSenseOf]->(concept)WHERE lemma.writtenRep = "clear"RETURN le.partOfSpeech AS PoS, concept.definition AS definitionThe results are numerous since clear is a word that can act as a noun, a verb, an adjective, or an adverb. The query returns the results in tabular form, and they match the ones you can get from querying WordNet through their public online search interface (https://oreil.ly/-BCyd) (see Figure 13-5).
Figure 13-5. WordNet results for the meaning of clear are the same in the Neo4j Browser (left) and WordNet’s web interface (right)
Example 13-26 shows how a slightly modified version of the query can be used to return a graph visualization of meanings (LexicalConcepts) of the word clear.
Example 13-26. A Cypher query that retrieves a graph visualization of meanings of the word clear
MATCH path = (lemma:Form)<-[:canonicalForm]-(:LexicalEntry)-[:sense]->()-[:isLexicalizedSenseOf]->()WHERE lemma.writtenRep = "clear"RETURN pathIn Figure 13-6, you can see the lexical concepts playing the role of a verb, adjectives, adverbs, and nouns in different components of the graph.
Figure 13-6. A graph visualization of the meanings of the word clear in Neo4j Bloom, with verbs, adjectives, adverbs, and nouns
Aggregations can be used to find the most polysemic words (words with multiple meanings) in English. It’s just about counting the number of Lexical Entry–Lexical Sense–Lexical Concept patterns coming out of a given word or set of words (WordNet uses the term lemma, or a canonical or dictionary form for this). The query in Example 13-27 produces a list of the five most polysemic words.
Example 13-27. A Cypher query to find the top five words with the most meanings
MATCH (lemma:Form)RETURN lemma.writtenRep AS lemma, size((lemma)<-[:canonicalForm]-(:LexicalEntry)-[:sense]->()) AS senseCountORDER BY senseCount DESC LIMIT 5The top five polysemic words in the current version of WordNet (2021) are shown in Table 13-1.
Table 13-1. Top five words with the most meanings
| lemma | senseCount |
|---|---|
| break | 75 |
| cut | 70 |
| run | 57 |
| play | 52 |
| make | 51 |
An inverse lookup is more interesting. With WordNet in a knowledge graph, you can find the opposite pattern by traversing the same graph pattern in the opposite direction, starting from a concept and navigating out to find all the words in the English language that can be used to express it. Figure 13-7 shows the three ways of expressing the concept of being unsuccessful.
Figure 13-7. Three ways to be unsuccessful
But which concepts have the most ways to express them? The query in Example 13-28 performs the traversals, aggregates the results, and sorts them by lemmas per lexical concept.
Example 13-28. A Cypher query that finds concepts that have many words to express them
MATCH (lemma:Form)<-[:canonicalForm]-(:LexicalEntry)-[:sense]->(s)-[:isLexicalizedSenseOf]->(con:LexicalConcept)RETURN con.definition AS concept, count(lemma.writtenRep) AS wordCount, collect(lemma.writtenRep) AS wordsORDER BY wordCount DESC LIMIT 10The results are quite interesting, should you choose to run that code snippet. Now you can dive into some of the more advanced features of WordNet.
Our WordNet graph is enriched with semantic relationships between lexical concepts. The list of relationships is quite extensive. You will find hypernymy (being more general than), hyponymy (being more specific than), meronymy (being part of), and many more. The complete list can be explored using the CALL db.relationshipTypes() method. The first two (hyper/hypo) form a taxonomy in the graph. You can navigate the graph to expand the analysis of a concept and find more specific (or alternatively, more generic) meanings for it. At the lemma level, this can be used to find more generic or more specific words.
The path in Figure 13-8 shows that sphere is a more general term for globe for the specific meaning a sphere on which a map (especially of the earth) is represented.
Figure 13-8. A globe is a kind of a sphere
On a more practical level, the exploration of these taxonomies has been used to define semantic similarity metrics between lexical concepts.
Graph-Based Semantic Similarity
Section titled “Graph-Based Semantic Similarity”Some of the most popular NLP libraries implement a number of standard semantic similarity metrics. These metrics turn out to be based on the exploration of paths in the lexical knowledge graph. You will explore three of the most commonly used ones and reproduce them using Cypher. You will also see how being able to customize the graph by adding terms and concepts specific to your domain can help you to use these metrics in multiple scenarios.
Path Similarity
Section titled “Path Similarity”The path similarity metric is based on the shortest path that connects the two lexical concepts in the taxonomy. Figure 13-9 shows how it is calculated.
Figure 13-9. Path similarity based on shortest path
Example 13-29. A Cypher query that implements path similarity
MATCH (a:LexicalConcept {uri: $a_id})MATCH (b:LexicalConcept {uri: $b_id})MATCH p = shortestPath((a)-[:hypernym*0..]-(b))WITH a, b, length(p) AS pathLenRETURN a.definition AS a_def, b.definition AS b_def, pathLen, 1.0/(1+pathLen) AS pathSimWhen run for params {a_id: "https://en-word.net/id/oewn-02086723-n", b_id: "https://en-word.net/id/oewn-02131817-n" } (the unique identifiers of the lexical concepts denoted by dog and lion, respectively), the Cypher query returns the results in Table 13-2.
Table 13-2. Dog and lion concepts, path length, and similarity
| a_def | b_def | pathLen | pathSim |
|---|---|---|---|
| “a member of the genus Canis (probably descended from the common wolf) that has been domesticated by man since prehistoric times; occurs in many breeds” | “large gregarious predatory feline of Africa and India having a tawny coat with a shaggy mane in the male” | 5 | 0.16666666666666666 |
The same results can be achieved using some popular NLP libraries. In this section, the Natural Language Toolkit for Python, more commonly known as NLTK (https://www.nltk.org), is used. The Python code snippet in Example 13-30 calls the path_similarity method in a synset to return that metric.
Example 13-30. Calling the path similarity method in Python via NLTK
from nltk.corpus import wordnet as wn
dog = wn.synset('dog.n.01')lion = wn.synset('lion.n.01')print(dog.definition())print(lion.definition())print(dog.path_similarity(lion))That code produces exactly the same results you got with the Cypher query, shown in Example 13-31.
Example 13-31. The results for path similarity from calling NLTK are the same as those from Cypher
a member of the genus Canis (probably descended from the common wolf) that has been domesticated by man since prehistoric times; occurs in many breedslarge gregarious predatory feline of Africa and India having a tawny coat with a shaggy mane in the male0.16666666666666666Why use Cypher instead of NLTK? There are several advantages to being able to control the implementation of the similarity algorithm:
- There is no dependency on the version of WordNet currently supported by NLTK. At this writing, NLTK supports WordNet 3.0 only, which is years behind the current version. Though in the example the results from the graph and those from NLTK are identical, it is easy to find cases where they are different.
- New lexical terms and associated lexical concepts can be added to the graph to provide domain-specific detail in areas not covered by WordNet. All that’s needed is to extend the graph by adding the relevant nodes and the relationships representing these entities.
- The previous point taken to the extreme means it’s possible to apply these metrics to any other taxonomic organization not necessarily based on WordNet.
- The algorithm itself can be modified and adapted if desired.
Some of these advantages will be evident on analysis of the metrics in the following sections.
Leacock-Chodorow Similarity
Section titled “Leacock-Chodorow Similarity”The Leacock-Chodorow similarity metric adds one extra element to the computation, and that is the depth of the taxonomy. You can easily compute the depth of a taxonomy as the greatest length of the path between any element and the root element. The way to get the depth of a taxonomy in Cypher is by using variable-length path expressions, as shown in Example 13-32.
Example 13-32. A Cypher query that finds the depth of the taxonomy
MATCH path = (leaf:LexicalConcept)-[:hypernym*0..]->(root)WHERE NOT EXISTS (()-[ :hypernym]->(leaf)) AND NOT EXISTS ((root)-[ :hypernym]->())RETURN max(length(path)) AS maxTaxonomyDepthThe query returns the value 19 for this graph, the global maximum.
There is not always a single root category that all categories are connected directly or indirectly to. There are graphs (WordNet is one of them) where there are multiple root elements or, in other words, multiple disconnected taxonomies. In those cases, you need to compute the depth of the taxonomy containing the elements being compared.
The Leacock-Chodorow similarity metric is defined by the formula in Figure 13-11.
Figure 13-11. The Leacock-Chodorow distance formula finds the depth of the taxonomy
This metric boosts similarities that happen in deeper hierarchies. And as in the previous case, the metric can be implemented using Cypher over your WordNet knowledge graph, as shown in Example 13-33.
Example 13-33. A Cypher implementation of the Leacock distance formula
MATCH (a:LexicalConcept {uri: $a_id})MATCH (b:LexicalConcept {uri: $b_id })MATCH p = shortestPath((a)-[:hypernym*0..]-(b))WITH a, b, length(p) AS pathLenRETURN a.definition AS a_def, b.definition AS b_def, pathLen, -log10(pathLen/(2.0*$depth)) AS LCSimAgain, using Cypher produces results similar to the ones obtained by using the NLTK version, shown in Example 13-34.
Example 13-34. Cypher and NLTK produce similar results
from nltk.corpus import wordnet as wn
dog = wn.synset('dog.n.01')lion = wn.synset('lion.n.01')print(dog.definition())print(lion.definition())print(wn.lch_similarity(dog, lion))Wu and Palmer Similarity
Section titled “Wu and Palmer Similarity”The Wu and Palmer similarity metric is based on the notion of the least common subsumer (LCS). The LCS is the most specific ancestor node of the two elements that are being compared.
The metric combines the depths of the two elements being compared and that of their LCS as defined by the formula in Figure 13-12.
Figure 13-12. The Wu-Palmer distance formula
To explain the calculation of the metric with the example you have been using in the previous sections, you need to provide additional context on the position in the overall WordNet taxonomy of the lexical concepts denoted by dog and lion. The diagram in Figure 13-13 shows the key elements for the Wu and Palmer metric.
Figure 13-13. The Wu-Palmer distance
To get the LCS with Cypher, you need to draw two variable-length patterns converging on the LCS, as shown in Example 13-35.
Example 13-35. Cypher implementation of the Wu-Palmer distance formula
MATCH (a:LexicalConcept {uri: $a_id})MATCH (b:LexicalConcept {uri: $b_id })MATCH p = (a)-[:hypernym*0..]->(lcs)<-[:hypernym*0..]-(b)WITH a, b, lcs, length(p) AS pathLenMATCH p = (lcs)-[:hypernym*0..]->(root)WHERE NOT (root)-[:hypernym]->()RETURN lcs.definition AS lcs_def, lcs.uri AS lcs_id, length(p) AS lcs_depthORDER BY pathLen LIMIT 1Table 13-3 shows the results.
Table 13-3. Using the Cypher implementation of Wu-Palmer distance formula to determine the LCS
| lcs_def | lcs_id | lcs_depth |
|---|---|---|
| a terrestrial or aquatic flesh-eating mammal | https://en-word.net/id/oewn-02077948-n | 11 |
Once you have the LCS, calculating the Wu and Palmer similarity metric is straightforward, as shown in Example 13-36.
Example 13-36. Calculating the Wu and Palmer similarity metric in Cypher
MATCH (a:LexicalConcept {uri: $a_id})MATCH (b:LexicalConcept {uri: $b_id })MATCH (lcs:LexicalConcept {uri: $lcs_id })MATCH a_to_lcs = (a)-[:hypernym*0..]->(lcs)MATCH b_to_lcs = (b)-[:hypernym*0..]->(lcs)WITH a, b, lcs, length(a_to_lcs) AS depth_a, length(b_to_lcs) AS depth_bRETURN (2.0 * $lcs_depth) / (2.0 * $lcs_depth + depth_a + depth_b) AS wp_simAs in the previous metrics, we’ll show how to achieve the same using NLTK directly. It’s not very different from what you saw for Leacock-Chodorow, just a different function name, as shown in Example 13-37.
Example 13-37. Calculating the Wu and Palmer similarity metric in Python
from nltk.corpus import wordnet as wn
dog = wn.synset('dog.n.01')lion = wn.synset('lion.n.01')print(dog.definition())print(lion.definition())print(wn.wup_similarity(dog, lion))One of the advantages of storing the lexical database in a knowledge graph is that it introduces transparency in an otherwise black box solution. This is reflected in the fact that the knowledge graph is a dynamic entity that allows for the addition of new elements.
What is the process for adding a new entity to the WordNet knowledge graph in Neo4j? Well, first you need to construct the pattern Form-Lexical Entry-Lexical Sense-Lexical Concept. This requires the concepts of proprietary software and open source software as hyponyms of software.
In Example 13-38, the set of CREATE statements in Cypher adds the nodes and relationships representing the lemmas (Form and LexicalEntry) that identify the sets of words proprietary software and closed-source software, both denoting the same meaning (LexicalConcept) with the following definition: computer software released under a license restricting use, study, or redistribution. To complete the pattern defined in WordNet, you must also include the intermediate LexicalSense.
Example 13-38. Adding lexical concepts to the knowledge graph in Cypher
CREATE (lc:LexicalConcept:Noun { subject:"noun.communication", partOfSpeech:"Noun", definition:"computer software released under a license restricting use, study or redistribution", uri:"https://custom.extension/id/15349-n", example:["the use of proprietary software is not allowed in our organization"]})CREATE (ls1:LexicalSense {uri: "https://custom.extension/lemma/prop-soft#15349"})CREATE (lc)<-[:isLexicalizedSenseOf]-(ls1)CREATE (le1:LexicalEntry:Noun { canonicalForm: "proprietary software", partOfSpeech: "Noun", uri: "https://custom.extension/lemma/prop-soft#prop-soft-n"})CREATE (ls1)<-[:sense]-(le1)CREATE (f1:Form { writtenRep: "proprietary software", uri: "https://custom.extension/lemma/prop-soft"})CREATE (le1)-[:canonicalForm]->(f1)
CREATE (ls2:LexicalSense {uri: "https://custom.extension/lemma/closed-soft#15348"})CREATE (lc)<-[:isLexicalizedSenseOf]-(ls2)CREATE (le2:LexicalEntry:Noun { canonicalForm: "closed-source software", partOfSpeech: "Noun", uri: "https://custom.extension/lemma/closed-soft#closed-soft-n"})CREATE (ls2)<-[:sense]-(le2)CREATE (f2:Form { writtenRep: "closed-source software", uri: "https://custom.extension/lemma/closed-soft"})CREATE (le2)-[:canonicalForm]->(f2)A similar script (excluded for brevity) would introduce the sets of words OSS and open source software denoting the same meaning (LexicalConcept) with the definition: software whose source code is available under an open source license.
Once the two new lexical concepts have been introduced, they need to be hooked to the existing hierarchy in WordNet with hypernym and the corresponding symmetric hyponym relationships, as shown in Example 13-39.
Example 13-39. Hooking added concepts to the existing hierarchy in Cypher
MATCH (prop:LexicalConcept { uri:"https://custom.extension/id/15349-n"})MATCH (oss:LexicalConcept { uri:"https://custom.extension/id/15350-n"})MATCH (sw:LexicalConcept { uri:"https://en-word.net/id/oewn-06578068-n"})MERGE (prop)-[:hypernym]->(sw)-[:hyponym]->(prop)MERGE (oss)-[:hypernym]->(sw)-[:hyponym]->(oss)The subgraph created by the previous scripts can be visually explored with the query in Example 13-40, which yields a graph like that shown in Figure 13-14.
Example 13-40. Query to explore the new lexical subgraph
MATCH p = (lc:LexicalConcept {uri:"https://en-word.net/id/oewn-06578068-n"})<-[:hypernym]-( )<-[:isLexicalizedSenseOf]-(ls)<-[:sense]-(le)-[:canonicalForm]->(f)RETURN pFigure 13-14. A visualization of the subgraph added to the WordNet knowledge graph
The extended graph is ready for semantic similarity computations, and the semantic similarity metrics discussed in this section can now be computed seamlessly (with exactly the same queries) on the newly created entities, producing the results in Table 13-4.
Table 13-4. Similarity metrics for the concepts added to the WordNet knowledge graph
| concept A | concept B | Path sim | Leacock-Chodorov sim | Wu and Palmer sim |
|---|---|---|---|---|
| software whose source code is available under an open source license | computer software released under a license restricting use, study, or redistribution | 0.4 | 0.846 | 0.973 |
This idea of modifying the graph can be generalized and the similarity metrics can be applied to a completely different knowledge graph as long as it contains some kind of hierarchical organization. This is the case with large knowledge graphs like Wikidata or DBPedia that have their entities classified in taxonomies using the rdf:SubClassOf (DBPedia) and wd:P279 (Wikidata) relationships, respectively.
You have seen that knowledge graphs import any kind of textual information, including any existing relationships, as with the many semantic relationships defined in WordNet. With your text in a knowledge graph, you can perform all the operations available in other tools using Cypher. You can add to your knowledge graph, adding domain-specific terms as needed. It’s a pattern often seen in the real world. For example, the German Center for Diabetes Research (DZD) has incorporated clinical trial data, its own research data, and the entirety of the PubMed database of published medical research into its knowledge graph.
Generating Natural Language in Rust (petgraph)
Section titled “Generating Natural Language in Rust (petgraph)”If you are using petgraph as an embedded knowledge graph in Rust, you can implement a natural language generation engine directly on top of your graph schema, much like the Cypher examples.
By iterating over nodes and edges in petgraph, you can concatenate strings to form simple Subject -> Predicate -> Object sentences.
Example 13-41. Generating simple sentences from petgraph
use petgraph::graph::{DiGraph, NodeIndex};
#[derive(Debug, Clone)]pub struct Entity { pub name: String,}
#[derive(Debug, Clone)]pub enum Relation { OfficerOf, WorksFor,}
pub fn generate_sentences(graph: &DiGraph<Entity, Relation>) -> Vec<String> { let mut sentences = Vec::new();
for edge in graph.edge_indices() { let (source_idx, target_idx) = graph.edge_endpoints(edge).unwrap(); let source = &graph[source_idx].name; let target = &graph[target_idx].name;
let predicate = match &graph[edge] { Relation::OfficerOf => "is an officer of", Relation::WorksFor => "works for", };
let sentence = format!("{} {} {}.", source, predicate, target); sentences.push(sentence); }
sentences}This Rust approach is incredibly fast and avoids any network overhead. To make it more dynamic (similar to the Ontology-driven Cypher approach in Example 13-21), you could store format string templates inside your Rust enum variants or load them from a local configuration file.
Summary
Section titled “Summary”In this chapter, you’ve seen a collection of powerful techniques and patterns for powering conversational systems with knowledge graphs. You’ve seen how specialist third-party tools and interoperability formats can be used to create compelling systems. Moreover, you’ve seen how straightforward building systems can be with commonplace graph database technology. You’ve reached an impressive level of understanding.
But that begs the question, “What’s next for knowledge graphs?” Chapter 14 makes some predictions about the future of knowledge graphs, based on everything you’ve learned in this book.