知识图谱task05

目录

    • 1.Neo4j的查询语言Cypher 介绍
    • 2.基于知识图谱的问题系统 主体类 AnswerSearching 框架介绍
      • 2.1.init
      • 2.2.根据不同的实体和意图构造cypher查询语句(question_parser)
      • 2.3.将问题转变为cypher查询语句(transfor_to_sql)
      • 2.4.根据不同意图,返回不同模板的答案(answer_template)
      • 2.5.执行cypher查询,返回结果(searching)

1.Neo4j的查询语言Cypher 介绍

“Cypher”是一个描述性的图形查询语言,允许不必编写图形结构的遍历代码对图形存储有表现力和效率的查询。

  • 思路:Cyper通过一系列不同的方法和建立于确定的实践为表达查询而激发的。许多关键字如like和order by是受SQL的启发。模式匹配的表达式来自于SPARQL。正则表达式匹配实现实用Scala programming language语言。
  • 与命令式语言的区别:Cypher是一个申明式的语言。对比命令式语言如Java和脚本语言如Gremlin和JRuby,它的焦点在于从图中如何找回(what to retrieve),而不是怎么去做。这使得在不对用户公布的实现细节里关心的是怎么优化查询。

eg查询症状:MATCH (d:Disease)-[:HAS_SYMPTOM]->(s) WHERE d.name='糖尿病' RETURN d.name,s.name
知识图谱task05_第1张图片

2.基于知识图谱的问题系统 主体类 AnswerSearching 框架介绍

在完成entity_extract之后(task03)做这一步search_answer.py:

class AnswerSearching:
    def __init__(self):
        pass
    # 主要是根据不同的实体和意图构造cypher查询语句
    def question_parser(self, data):
        """
        主要是根据不同的实体和意图构造cypher查询语句
        :param data: {"Disease":[], "Alias":[], "Symptom":[], "Complication":[]}
        :return:
        """
        pass
    # 将问题转变为cypher查询语句
    def transfor_to_sql(self, label, entities, intent):
        """
        将问题转变为cypher查询语句
        :param label:实体标签
        :param entities:实体列表
        :param intent:查询意图
        :return:cypher查询语句
        """
        pass
    # 执行cypher查询,返回结果
    def searching(self, sqls):
        """
        执行cypher查询,返回结果
        :param sqls:
        :return:str
        """
        pass
    # 根据不同意图,返回不同模板的答案
    def answer_template(self, intent, answers):
        """
        根据不同意图,返回不同模板的答案
        :param intent: 查询意图
        :param answers: 知识图谱查询结果
        :return: str
        """
        pass

2.1.init

from py2neo import Graph #在Python中我们使用py2neo进行查询
graph = Graph("http://localhost:7474", username="neo4j", password="neo4j")
#连接上neo4j数据库

2.2.根据不同的实体和意图构造cypher查询语句(question_parser)

 def question_parser(data):
        """
        主要是根据不同的实体和意图构造cypher查询语句
        :param data: {"Disease":[], "Alias":[], "Symptom":[], "Complication":[]}
        :return:
        """
        sqls = []
        if data:
            for intent in data["intentions"]:
                sql_ = {}
                sql_["intention"] = intent
                sql = []
                if data.get("Disease"):
                   sql = transfor_to_sql("Disease", data["Disease"], intent)
                elif data.get("Alias"):
                    sql = transfor_to_sql("Alias", data["Alias"], intent)
                elif data.get("Symptom"):
                    sql = transfor_to_sql("Symptom", data["Symptom"], intent)
                elif data.get("Complication"):
                    sql = transfor_to_sql("Complication", data["Complication"], intent)

                if sql:
                    sql_['sql'] = sql
                    sqls.append(sql_)
        return sql

2.3.将问题转变为cypher查询语句(transfor_to_sql)

def transfor_to_sql(label, entities, intent):
        """
        将问题转变为cypher查询语句
        :param label:实体标签
        :param entities:实体列表
        :param intent:查询意图
        :return:cypher查询语句
        """
        if not entities:
            return []
        sql = []

        # 查询症状
        if intent == "query_symptom" and label == "Disease":
            sql = ["MATCH (d:Disease)-[:HAS_SYMPTOM]->(s) WHERE d.name='{0}' RETURN d.name,s.name".format(e)
                   for e in entities]
        # 查询治疗方法
        if intent == "query_cureway" and label == "Disease":
            sql = ["MATCH (d:Disease)-[:HAS_DRUG]->(n) WHERE d.name='{0}' return d.name,d.treatment," \
                   "n.name".format(e) for e in entities]
         # 查询治疗周期
        if intent == "query_period" and label == "Disease":
            sql = ["MATCH (d:Disease) WHERE d.name='{0}' return d.name,d.period".format(e) for e in entities
        ...

2.4.根据不同意图,返回不同模板的答案(answer_template)

在searching中调用

def answer_template(intent, answers):
        """
        根据不同意图,返回不同模板的答案
        :param intent: 查询意图
        :param answers: 知识图谱查询结果
        :return: str
        """
        final_answer = ""
        if not answers:
            return ""
        # 查询症状
        if intent == "query_symptom":
            disease_dic = {}
            for data in answers:
                d = data['d.name']
                s = data['s.name']
                if d not in disease_dic:
                    disease_dic[d] = [s]
                else:
                    disease_dic[d].append(s)
            i = 0
            for k, v in disease_dic.items():
                if i >= 10:
                    break
                final_answer += "疾病 {0} 的症状有:{1}\n".format(k, ','.join(list(set(v))))
                i += 1
            ...

2.5.执行cypher查询,返回结果(searching)

def searching(sqls):
        """
        执行cypher查询,返回结果
        :param sqls:
        :return:str
        """
        final_answers = []
        for sql_ in sqls:
            intent = sql_['intention']
            queries = sql_['sql']
            answers = []
            for query in queries:
                ress = graph.run(query).data()
                answers += ress
            final_answer = answer_template(intent, answers)
            if final_answer:
                final_answers.append(final_answer)
        return final_answers

你可能感兴趣的:(知识图谱,知识图谱)