11
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

リレーショナル・テーブルを土台にしてプロパティ・グラフを作成し Select AI の精度を高める

11
Last updated at Posted at 2026-11-09

はじめに

Select AI は大変便利なのですが、どんなにコメントやアノテーションをつけても、うまく JOIN してくれないことってありますよね。

こんなときグラフを使うと、データの「関係の意味」を明示でき、LLM がクエリを作るときの推測を減らすことができます。 リレーショナル・テーブルでテーブル間の関係をたどるような質問で正しいいクエリが生成できない場面では、グラフを用いる価値がありそうです。

Oracle の SQL プロパティ・グラフは、既存のリレーショナル・テーブル上に、データを頂点 (VERTEX)・エッジ (EDGE)・プロパティとして扱うための論理的なグラフ構造を定義する機能です。データの実体は元のテーブルに保持され、グラフ作成時に別のデータストアへコピーする必要はありません。

Select AIは、リレーショナル・テーブルだけではなく、Oracle プロパティ・グラフに対してプロパティ・グラフ問合せ (PGQ) を生成することができます。グラフ定義を LLM に提供することで、データ間の関係を明示したうえで、自然言語の質問から PGQ を生成できます。

object_list 属性に1つ以上のプロパティ・グラフが定義された AIプロファイルを作成すると、AIプロファイルで定義された LLM は、指定されたプロパティ・グラフのコンテキストを使用してプロンプトを解釈します。

コンテキスト不足のリレーショナル・テーブルで実験

Autonomous AI Database を使って実際にやってみましょう。
一連の作業は、Select AI for Python を使用して、Notebook上で行います。Notebook は GitHub に公開しています(実行結果が一部この投稿と異なっている箇所がありますが、コンテキスト不足故に実行結果に揺らぎがある証拠と考えて下さい)。

とりあえず、準備から
image.png

$\small \textsf{script}$
# 準備
import dotenv, os, subprocess
import select_ai
import oracledb
import pandas as pd

dotenv.load_dotenv()
user = os.getenv("user")
password = os.getenv("password")
dsn=os.getenv("dsn")
admin_password=os.getenv("admin_password")

関数は、後で使います。

image.png

$\small \textsf{script}$
def execute_sql_script(script, print_stdout=False):
    """ SQLスクリプトを実行する """
    print(f"script={script}")
    cmd = f"""sql "{user}/{password}@{dsn}" @{script}"""
    result = subprocess.run(cmd, shell=True, check=True, capture_output=True, text=True)
    if print_stdout:
        print(result.stdout)

def execute_sql(sql, print_sql=False):
    """ SQL文を実行する、Pandasで結果を表示する """
    if print_sql:
        print(f"sql={sql}")
    with oracledb.connect(user=user, password=password, dsn=dsn) as con:
        with con.cursor() as cur:
            cur.execute(sql)
            columns = [column[0] for column in cur.description]
            df = pd.DataFrame(cur.fetchall(), columns=columns)
            display(df.style.hide(axis="index"))

def execute_query(profile, query):
    """ Select AI を使って自然言語の問い合わせを実行する """
    try:
        profile = select_ai.Profile(profile_name=profile)
        sql = profile.show_sql(query)
        print(f"### profile={profile.profile_name}")
        print(query)
        print("--- SQL ---")
        print(sql)
        print("--- RESULT ---")
        execute_sql(sql)
    except Exception as e:
        print(e)

まず、無味が不明瞭な4つのテーブルを作成します。
本来の意味は以下の通りなのですが、実験のためにテーブル名、カラム名は、敢えて意味を持たせていません。

テーブル一覧

テーブル名 意味
RESIDENTS 住民
RESIDENTS_SUB1 住民の収入
RESIDENTS_SUB2 住民の支出
RESIDENTS_SUB3 住民の支出明細

RESIDENTS(住民)

カラム名 意味
ID 住民を識別するID
NAME 住民の名前

RESIDENTS_SUB1(住民の収入)

カラム名 意味
ID 住民のID(RESIDENTS.IDに対応)
VALUE 収入金額

RESIDENTS_SUB2(住民の支出)

カラム名 意味
ID 住民のID(RESIDENTS.IDに対応)
VALUE 支出金額の合計

RESIDENTS_SUB3(住民の支出明細)

カラム名 意味
ID 支出明細を識別するID
SUB_ID 住民のID(RESIDENTS_SUB2.IDに対応)
KIND 支出の種類(食費、その他など)
VALUE 明細ごとの支出金額

image.png

$\small \textsf{ddl.sql}$
DROP TABLE IF EXISTS DEMO.RESIDENTS ;
DROP TABLE IF EXISTS DEMO.RESIDENTS_SUB1 ; 
DROP TABLE IF EXISTS DEMO.RESIDENTS_SUB2 ;
DROP TABLE IF EXISTS DEMO.RESIDENTS_SUB3 ;

CREATE TABLE DEMO.RESIDENTS 
    ( 
     ID   VARCHAR2 (8) , 
     NAME VARCHAR2 (20) 
    ) 
    LOGGING 
;

ALTER TABLE DEMO.RESIDENTS 
    ADD CONSTRAINT RESIDENTS_PK PRIMARY KEY ( ID ) 
    USING INDEX LOGGING ;

---

CREATE TABLE DEMO.RESIDENTS_SUB1 
    ( 
     ID    VARCHAR2 (8) , 
     VALUE NUMBER 
    ) 
    LOGGING 
;

ALTER TABLE DEMO.RESIDENTS_SUB1 
    ADD CONSTRAINT RESIDENTS_SUB1_PK PRIMARY KEY ( ID ) 
    USING INDEX LOGGING ;

---

CREATE TABLE DEMO.RESIDENTS_SUB2 
    ( 
     ID    VARCHAR2 (8) , 
     VALUE NUMBER 
    ) 
    LOGGING 
;

ALTER TABLE DEMO.RESIDENTS_SUB2 
    ADD CONSTRAINT RESIDENTS_SUB2_PK PRIMARY KEY ( ID ) 
    USING INDEX LOGGING ;

---

CREATE TABLE DEMO.RESIDENTS_SUB3 
    ( 
     ID     VARCHAR2 (8) , 
     SUB_ID VARCHAR2 (8) , 
     KIND   VARCHAR2 (20) , 
     VALUE  NUMBER 
    ) 
    LOGGING 
;

ALTER TABLE DEMO.RESIDENTS_SUB3 
    ADD CONSTRAINT RESIDENTS_SUB3_PK PRIMARY KEY ( ID ) 
    USING INDEX LOGGING ;

EXIT;
$\small \textsf{dml.sql}$
INSERT INTO DEMO.RESIDENTS VALUES ('1', 'Michael');
INSERT INTO DEMO.RESIDENTS VALUES ('2', 'John');
INSERT INTO DEMO.RESIDENTS VALUES ('3', 'Patty');

INSERT INTO DEMO.RESIDENTS_SUB1 VALUES ('1', 1000);
INSERT INTO DEMO.RESIDENTS_SUB1 VALUES ('2', 1200);
INSERT INTO DEMO.RESIDENTS_SUB1 VALUES ('3', 1900);

INSERT INTO DEMO.RESIDENTS_SUB2 VALUES ('1',  800);
INSERT INTO DEMO.RESIDENTS_SUB2 VALUES ('2', 1500);
INSERT INTO DEMO.RESIDENTS_SUB2 VALUES ('3', 2000);

INSERT INTO DEMO.RESIDENTS_SUB3 VALUES ('1', '1', '食費',  200);
INSERT INTO DEMO.RESIDENTS_SUB3 VALUES ('2', '1', 'その他',  600);
INSERT INTO DEMO.RESIDENTS_SUB3 VALUES ('3', '2', '食費',  500);
INSERT INTO DEMO.RESIDENTS_SUB3 VALUES ('4', '2', 'その他', 1000);
INSERT INTO DEMO.RESIDENTS_SUB3 VALUES ('5', '3', '食費',  600);
INSERT INTO DEMO.RESIDENTS_SUB3 VALUES ('6', '3', 'その他', 1300);

EXIT;

image.png

image.png

これではどっちが収入 or 支出のテーブルか分かりませんし、明細テーブルがどっちと関連しているかも判別できませんね。

ではこれからリレーショナル・テーブルとプロパティ・グラフ双方に対して、以下の自然言語での問い合わせを実施して、結果を確認してみようと思います。

  • 住民の名前を全員表示して下さい
  • 各住民の収入はいくらですか?
  • 支出が一番多い住民と支出額は?
    (正解: Patty, 2000)
  • 支出に占める食費の割合が一番高い住民の名前とパーセンテージを教えて
    (正解: John, 33.3%)

最初に Select AI の事前準備をやっておきます。
(今回は LLM の呼び出しにリソース・プリンシパルを使います)

image.png

$\small \textsf{script}$
# Database に接続
select_ai.connect(user=user, password=password, dsn=dsn)

# Resource Principal の設定
with oracledb.connect(user="admin", password=admin_password, dsn=dsn) as con:
    with con.cursor() as cur:
        cur.execute(f"call DBMS_CLOUD_ADMIN.ENABLE_RESOURCE_PRINCIPAL(username => '{user}')")

リレーショナル・テーブルに対する Select AI

リレーショナル・テーブルでは SELECT AI でうまく問い合わせできないことを確かめていきましょう。

image.png

$\small \textsf{script}$
provider = select_ai.OCIGenAIProvider(
    region="us-chicago-1", 
    model="xai.grok-4.3",
    oci_apiformat="GENERIC"
)
profile_attributes = select_ai.ProfileAttributes(
    credential_name="OCI$RESOURCE_PRINCIPAL",
    object_list=[
                    {"owner": "DEMO", "name": "RESIDENTS"},
                    {"owner": "DEMO", "name": "RESIDENTS_SUB1"},
                    {"owner": "DEMO", "name": "RESIDENTS_SUB2"},
                    {"owner": "DEMO", "name": "RESIDENTS_SUB3"}
                 ],
    provider=provider,
    max_tokens=4096,
    comments=True
)
profile = select_ai.Profile(
    profile_name="DEMO_PROFILE_PLAIN",
    attributes=profile_attributes,
    description="AI Profile for Relational tables",
    replace=True,
)

image.png

流石にこれくらいはイケますが ...

image.png

ちょっと意味のない JOIN になってしまいました。当てずっぽうです。

image.png

間違い...

image.png

これも間違い...

正しい答えは得られませんでした(想定通り)。

プロパティ・グラフを使った Select AI

ここでプロパティ・グラフの登場です。
リレーショナル・テーブル間の関係を補完するように、プロパティ・グラフを作成します。

CREATE PROPERTY GRAPH RESIDENTS_GRAPH
VERTEX TABLES (
    DEMO.RESIDENTS AS RESIDENT KEY (ID)
        LABEL RESIDENT
        PROPERTIES (ID, NAME),

    DEMO.RESIDENTS_SUB1 AS INCOME KEY (ID)
        LABEL INCOME
        PROPERTIES (ID, VALUE AS AMOUNT),

    DEMO.RESIDENTS_SUB2 AS EXPENSE KEY (ID)
        LABEL EXPENSE
        PROPERTIES (ID, VALUE AS AMOUNT),

    DEMO.RESIDENTS_SUB3 AS EXPENSE_DETAIL KEY (ID)
        LABEL EXPENSE_DETAIL
        PROPERTIES (ID, KIND, VALUE AS AMOUNT)
)
EDGE TABLES (
    DEMO.RESIDENTS_SUB1 AS HAS_INCOME KEY (ID)
        SOURCE KEY (ID) REFERENCES RESIDENT (ID)
        DESTINATION KEY (ID) REFERENCES INCOME (ID)
        LABEL HAS_INCOME
        NO PROPERTIES,

    DEMO.RESIDENTS_SUB2 AS HAS_EXPENSE KEY (ID)
        SOURCE KEY (ID) REFERENCES RESIDENT (ID)
        DESTINATION KEY (ID) REFERENCES EXPENSE (ID)
        LABEL HAS_EXPENSE
        NO PROPERTIES,

    DEMO.RESIDENTS_SUB3 AS HAS_DETAIL KEY (ID)
        SOURCE KEY (SUB_ID) REFERENCES EXPENSE (ID)
        DESTINATION KEY (ID) REFERENCES EXPENSE_DETAIL (ID)
        LABEL HAS_DETAIL
        NO PROPERTIES
);

プロパティ・グラフでは、VERTEX(頂点) と EDGE(辺)を定義することによってオブジェクト・クラスとその関係性を表現します。

Autonomous AI Database 付属の Graph Studio の Modeler で表示すると、このようにビジュアルにグラフの構造が確認できます。

image.png

うまくテーブル間の関係性が表現されていますね。
では、Select AI を実行してみましょう。

最初にグラフと Select AI プロファイルを作成します。
Select AI プロファイル の object_list プロパティに先ほど作成したグラフ RESIDENTS_GRAPH を設定します。

image.png

$\small \textsf{script}$
# SQL Property Graph の作成
execute_sql_script("create_graph.sql")

# DEMO_PROFILE_GRAPH を作成
provider = select_ai.OCIGenAIProvider(
    region="us-chicago-1", 
    model="xai.grok-4.3",
    oci_apiformat="GENERIC"
)
profile_attributes = select_ai.ProfileAttributes(
    credential_name="OCI$RESOURCE_PRINCIPAL",
    object_list=[
                    {"owner": "DEMO", "name": "RESIDENTS_GRAPH"}
                 ],
    provider=provider,
    max_tokens=4096,
    comments=True
)
profile = select_ai.Profile(
    profile_name="DEMO_PROFILE_GRAPH",
    attributes=profile_attributes,
    description="AI Profile for Graph tables",
    replace=True,
)

同じ問い合わせを投げてみます。

image.png

image.png

image.png

image.png

各問い合わせに正しく回答しています。グラフの問い合わせ PGQ の MATCH 句で正しい参照関係を表現できているからです。

MATCH (r IS "RESIDENT")

MATCH (r IS "RESIDENT") -[e IS "HAS_INCOME"]-> (i IS "INCOME")

MATCH (r IS "RESIDENT") -[he IS "HAS_EXPENSE"]-> (exp IS "EXPENSE")

MATCH (resident IS "RESIDENT") 
    -[he IS "HAS_EXPENSE"]-> 
        (expense IS "EXPENSE") 
            -[hd IS "HAS_DETAIL"]->
                (detail IS "EXPENSE_DETAIL")

では、Select AI は実際にどんなプロンプトを作って LLM に投げているのでしょうか?

image.png

$\small \textsf{script}$
profile = select_ai.Profile(profile_name="DEMO_PROFILE_GRAPH")
prompt = profile.show_prompt("支出に占める食費の割合が一番高い住民の名前とパーセンテージを教えて")

import json

instructions = json.loads(prompt) # type:list
for inst in instructions:
    print("########")
    print(inst["content"][0]["text"].replace("\\n", "\n"))
$\small \textsf{出力結果}$
# Role and Objective
You are an Oracle SQL/PGQ expert.
SQL/PGQ is an extension of the SQL query language for the property graph data
model that allows users to specify high-level graph patterns matched against
vertices and edges. It integrates with all existing SQL functionalities and is
supported in Oracle Database.
Your role is to help users define and query property graphs using SQL/PGQ.
Always reason step-by-step, produce correct and complete queries, and apply
best practices from Oracle documentation.
# Context and Knowledge Use
Note the following rules about Oracle SQL/PGQ:

- to access graph data, use the GRAPH_TABLE operator, which can be used anywhere
  a table can be used
- property graph comments, when present in the context, describe the graph's
  business meaning and intended use
- use property graph comments as semantic guidance when choosing the graph and
  interpreting labels, properties and relationships
- do not invent labels, properties or relationships that are not present in
  the graph definition
- only add a WHERE clause when the user explicitly asks for a property or
  value filter, or when a filter is strictly necessary to answer the question
- for general relationship or traversal questions, do not invent filters
- never invent placeholder predicates or arbitrary string comparisons just to
  satisfy a prompt rule
- the GRAPH_TABLE operator contains the name of the graph, a MATCH clause, an
  optional WHERE clause and a COLUMNS clause. Other SQL clauses like GROUP BY
  must be used outside of GRAPH_TABLE
- the MATCH clause is used to define a graph pattern to be matched
- vertex patterns take the form of (v) where v is the name of variable
- edge patterns take the form of -[e]-> for outgoing edges, <-[e]- for incoming
  edges or -[e]- for an edge in either direction, where e is the variable name
- resolve source and destination roles from the graph's SOURCE KEY and
  DESTINATION KEY definitions and the relationship meaning before adding
  endpoint filters; variable names and left/right position do not define roles
- for transfer edges directed from sender to recipient, apply "received by"
  filters to the destination/recipient and "sent by" filters to the source/sender
- verify each endpoint filter against the arrow direction, including patterns
  written right-to-left: in (recipient)<-[transfer]-(sender), the recipient is
  the destination and the sender is the source
- for direct-neighbor questions such as "people connected to X", when neither
  the request nor graph semantics specifies direction, match an edge in either
  direction using -[e]-
- for these neighbor questions, bind the named entity to one vertex variable,
  apply its property filter only to that variable, and project the opposite
  vertex's requested properties as the neighbor result
- prefer one GRAPH_TABLE with an either-direction edge over separate incoming
  and outgoing UNION branches when they express the same neighbor search.
  Do not introduce endpoint-switching CASE expressions or nested graph queries
  when the opposite endpoint is already bound
- for a list of unique neighbors, eliminate duplicate neighbors caused by
  reciprocal or parallel edges. Preserve multiplicity for edge/path questions
  and respect explicitly requested traversal direction
- to search vertices with a specific label, use the IS keyword: (v is "LABEL")
- resolve vertex and edge labels from the supplied property graph definition
  before writing MATCH patterns
- when an element declares explicit LABEL clauses, use those labels after IS;
  its underlying table name or element alias is not automatically a label
- when an element has no explicit LABEL clause, its default label is its
  element alias, or its table name when no alias is specified
- preserve label identifiers exactly, including non-English characters and
  case, and use double quotes when referencing them in MATCH
- to search vertices with one of multiple possible labels, use the IS keyword
  and provide a list of labels separated by a | character:
  (v is "LABEL" | "LABEL2" | "LABEL3")
- the same rules apply for edges: -[e is "LABEL" | "LABEL2" | "LABEL3"]->
- NEVER use Cypher-style label syntax such as (v: "LABEL") or
  -[: "LABEL"]->; Oracle SQL/PGQ requires the IS keyword, for example:
  (v IS "LABEL") and -[e IS "LABEL"]->
- ALWAYS declare a variable name for every edge pattern, including labeled
  edges. For example, use -[likes_edge IS "PERSONLIKEPOST"]-> and not
  -[: "PERSONLIKEPOST"]->
- the IS clause is optional, use (v) to match all vertices or -[e]- to match all
  edges
- paths of edges can be matched by applying a quantifier after an edge pattern:
  -[e]-> * for 0 or more, -[e]-> + for 1 or more and -[e]-> {n, m} for at least
  n and at most m edges in the path
- properties can be accessed for vertices v and edges e using v.property_name
  and e.property_name inside the WHERE and COLUMNS clauses of the GRAPH_TABLE
  operator
- to make properties and other expressions based on vertices and edges
  accessible outside of the GRAPH_TABLE operator, list the expression in the
  COLUMNS clause and assign an alias. The alias (and not the original
  expression) can then be used outside of GRAPH_TABLE
- variables declared in MATCH are scoped only inside GRAPH_TABLE. Use them
  only in MATCH, WHERE, and COLUMNS; never use them as table aliases in outer
  SQL clauses
- every expression used outside of GRAPH_TABLE must have an explicit COLUMNS
  alias. In outer SELECT, DISTINCT, WHERE, GROUP BY, HAVING, ORDER BY, scalar
  functions, and aggregate functions, use only COLUMNS aliases
- use exported aliases exactly as declared; do not pluralize or rename an
  input alias when selecting it. Introduce an aggregate result alias with AS
  in the outer SELECT instead
- map each requested filter to the property that represents that attribute
  in the graph metadata. Do not substitute an identifier or name merely
  because it is also requested in the output; filter before aggregation
  unless the request explicitly concerns an aggregate result
- for natural-language string equality filters on graph properties, use
  case-insensitive matching unless the user explicitly requests case-sensitive
  matching
- a request to format an amount for a country or currency is display formatting
  only. Do not invent a currency property, exchange rate, sender, recipient,
  date filter, or currency conversion unless graph metadata supplies those
  facts
- for localized monetary display, project the numeric value with a COLUMNS
  alias and apply TO_CHAR only to that alias outside GRAPH_TABLE. Use FM for
  fill mode, L for the local-currency symbol, and G and D for group and decimal
  separators, with explicit NLS_NUMERIC_CHARACTERS and NLS_CURRENCY settings.
  NLS_CURRENCY alone does not print a symbol without L in the format model
- for monetary amounts requiring two fractional digits, use D00; FM with D99
  can suppress a trailing zero. A suitable format model is FML999G999G990D00
- NLS_NUMERIC_CHARACTERS lists the decimal separator first and group separator
  second; use '.,' for American formatting and ',.' for other countries
- translate territory requests into explicit supported formatting parameters;
  do not pass NLS_TERRITORY in the NLS parameter string of numeric TO_CHAR
- when a user asks to display a graph date using a named calendar, treat it as
  display formatting, not time-zone conversion. Use the requested date or
  timestamp property from graph metadata; do not replace it with SYSDATE, query
  DUAL, substitute another property, or use AT TIME ZONE unless the user
  explicitly requests the current date or a time-zone conversion
- for named-calendar display, project the date or timestamp property with a
  COLUMNS alias and apply TO_CHAR only to that alias outside GRAPH_TABLE, using
  an explicit NLS_CALENDAR setting. Use a valid Oracle calendar name exactly;
  preserve spaces in multiword names such as ARABIC HIJRAH and never replace
  them with underscores
- in the NLS parameter string, leave single-word calendar values unquoted and
  enclose multiword values in single quotes. Double those single quotes inside
  the SQL string literal. Valid SQL literals are 'NLS_CALENDAR=PERSIAN' and
  'NLS_CALENDAR=''ARABIC HIJRAH'''; do not use double quotes around calendar
  values or leave a multiword value unquoted
- instead of projecting vertices and edges, project their identifier in the
  COLUMNS clause using VERTEX_ID(v) or EDGE_ID(e)
- the WHERE clause inside GRAPH_TABLE can be used to add conditions for matching
  vertices and edges, based on their properties: WHERE v."PROPERTY" = 123
- for filters that name a calendar month, such as January, prefer a numeric
  date-part predicate on DATE or TIMESTAMP properties: EXTRACT(MONTH FROM
  date_property) = month_number, where January is 1 and December is 12
- do not compare TO_CHAR(date_property, 'MONTH') directly to an unpadded month
  name because the MONTH format model can add trailing blanks
- if a textual full-month comparison is specifically required, use
  TRIM(TO_CHAR(date_property, 'MONTH')) or the FM format modifier; specify
  NLS_DATE_LANGUAGE when the requested month language matters
- Do not use single quotes (') for identifiers, use double quotes (")
- Define variable names for all nodes and edges in the MATCH clause
- Use MATCH variable names consistently only within MATCH, WHERE, and COLUMNS
- Ensure every variable used in the query is declared in the MATCH pattern
- Do not use unsupported quantifiers or syntax like *?, +? when writing path
  patterns
- Avoid reusing the same variable name as both singleton and grouped variable
- Ensure all opening paretheses '(' have matching closing parentheses ')'
- Use IS "LABEL_NAME" instead of :"LABEL_NAME", when matching labels, e.g.:
  use [e IS "KNOWS"] instead of [e:"KNOWS"].
- For complete MATCH patterns, follow this valid/invalid form exactly:
```sql
-- valid
MATCH (person IS "PERSON") -[likes_edge IS "PERSONLIKEPOST"]-> (post IS "POST")

-- invalid
MATCH (person: "PERSON") -[: "PERSONLIKEPOST"]-> (post: "POST")
```
- always add an extra suffix to the variable names when using Oracle reserved
  keywords, e.g.: use (start_person IS "PERSON") instead of (start IS "PERSON")
- to check if two vertices are equal, you CANNOT use v1 = v2, you need to use
  VERTEX_EQUAL instead
- for example to SELECT the ID and a property "MY_PROPERTY" for a vertex with
  the "AGE" property being greater than 20, project VERTEX_ID and the property
  in COLUMNS, then list the alias in the SELECT clause (outside of GRAPH_TABLE):
```sql
SELECT person_id, person_name
FROM GRAPH_TABLE("STUDENT_NETWORK"
MATCH (v is "PERSON")
WHERE v."AGE" > 20
COLUMNS( VERTEX_ID(v) as person_id, v."NAME" AS person_name ))
```
- the COLUMNS clause must not be empty, you can add a dummy value if no property
  is needed:
```sql
SELECT COUNT(*) AS total_edge_count
FROM GRAPH_TABLE("STUDENT_NETWORK"
MATCH (v) -[e]-> (w)
COLUMNS (1 as dummy_value))
```
- for simple vertex or edge patterns, aggregate outside GRAPH_TABLE. Project
  the scalar value in COLUMNS, then use the aggregation function in the outer
  SELECT:
```sql
SELECT AVG(person_age) AS average_age
FROM GRAPH_TABLE("STUDENT_NETWORK"
MATCH (v is "PERSON")
COLUMNS (v."AGE" as person_age))
```
- to aggregate simple edge identifiers into one list, project EDGE_ID in
  COLUMNS and apply JSON_ARRAYAGG outside GRAPH_TABLE:
```sql
SELECT JSON_ARRAYAGG(edge_id ORDER BY edge_id) AS edge_ids
FROM GRAPH_TABLE("STUDENT_NETWORK"
MATCH (v) -[e]-> (w)
COLUMNS (EDGE_ID(e) as edge_id))
```
- do not use aggregate functions inside COLUMNS for simple singleton
  variables, for example JSON_ARRAYAGG(EDGE_ID(e)) is invalid for the pattern
  MATCH (v) -[e]-> (w)
- when the request requires a list per entity, export the grouping keys and
  individual values in COLUMNS. Use GROUP BY on the exported keys and
  JSON_ARRAYAGG(value_alias) AS list_alias in the outer SQL query
- for more complex path patterns, add the quantifier to a path pattern, ex:
  ( (src) -[edge]-> (dst) )*
- this way, you can also add filters on properties of vertices along the path,
  for instance, the following query matches a path from src to dst where each
  vertex along the path is older than the previous vertex
```sql
SELECT *
FROM GRAPH_TABLE("MY_GRAPH"
MATCH (src) ((v1) -[e]-> (v2) WHERE v1."AGE" < v2."AGE")* (dst)
COLUMNS(JSON_ARRAYAGG(v1."AGE") as sources_ages,
        JSON_ARRAYAGG(EDGE_ID(e)) as edge_ids))
```
- aggregate functions inside GRAPH_TABLE COLUMNS are valid only when they
  aggregate over grouped variables from a quantified path pattern, such as
  variables inside ()*, ()+, or (){n,m}. Use JSON_ARRAYAGG to aggregate values
  in a list along such a path:
```sql
SELECT edge_ids, min_account_balance
FROM GRAPH_TABLE("MY_GRAPH"
MATCH (path_start) ( (v1 IS "ACCOUNT") -[e]-> (v2) ){1,10} (path_end)
COLUMNS(JSON_ARRAYAGG(EDGE_ID(e)) as edge_ids,
        MIN(v1."BALANCE") as min_account_balance))
```
# Common Errors to Avoid
ORA-00904: Invalid identifier, as a solution check property or column names.
ORA-40954: Unknown label. Check names following IS against the graph's explicit
           or default labels; do not substitute underlying table names or
           element aliases for explicitly declared labels.
ORA-40983: Invalid property name, as a solution upper case quoted properties
           like "age"; use "AGE".
ORA-40985: Unsupported quantifier, as a solution only use *, +, ? in path
           patterns where allowed.
ORA-40997: Invalid path pattern, as a solution make sure path syntax is correct
           (no typos).
ORA-00907: Missing parenthesis, as a solution check (), especially in MATCH and
           WHERE.
ORA-00928: SELECT missing, as a solution all subqueries must begin with SELECT.
ORA-12702: Invalid NLS parameter string. Use only NLS parameters supported by
           the called SQL function. For NLS_CALENDAR, use a valid calendar name
           and single-quote multiword values inside the parameter string,
           doubling those single quotes inside the SQL string literal.
ORA-49001: Singleton/group name conflict, as a solution don't reuse the same
           variable for both.
ORA-49011: A group function inside GRAPH_TABLE() must have a group reference,
           as a solution aggregate outside GRAPH_TABLE for simple patterns, or
           aggregate inside COLUMNS only over a quantified path/group variable.
DPY-4010: Bind variable not provided, as a solution use IS when matching labels.
ORA-42414: Mixed property types, as a solution columns should return same data
           types if restricted.
ORA-40957: Missing variable name, as a solution each pattern part must have a
           variable name.
# Workflow
When writing queries:
1. Determine which schema should be used based on the user question
2. Respond with just the final SQL/PGQ query
3. Remember to pay attention to the rules about Oracle SQL/PGQ
# Output Formatting
Respond with just the final SQL/PGQ query
--'住民の収入・支出・支出明細を表すグラフ。
RESIDENTは住民、INCOMEは収入、EXPENSEは支出、
EXPENSE_DETAILは支出明細。
HAS_EXPENSEは住民と支出、
HAS_EXPENSE_DETAILSは支出と各明細を結ぶ。
HAS_EXPENSE_DETAILSのKINDの値には 食費 と その他 の値が含まれる。'
CREATE PROPERTY GRAPH "DEMO"."RESIDENTS_GRAPH"
      VERTEX TABLES (
        "DEMO"."RESIDENTS"
          LABEL "RESIDENT"
          PROPERTIES("ID", "NAME"),
        "DEMO"."RESIDENTS_SUB1"
          LABEL "INCOME"
          PROPERTIES("ID", "AMOUNT"),
        "DEMO"."RESIDENTS_SUB2"
          LABEL "EXPENSE"
          PROPERTIES("ID", "AMOUNT"),
        "DEMO"."RESIDENTS_SUB3"
          LABEL "EXPENSE_DETAIL"
          PROPERTIES("ID", "KIND", "AMOUNT")
      )
      EDGE TABLES("DEMO"."RESIDENTS_SUB1" SOURCE "RESIDENT", DESTINATION "INCOME"
          LABEL "HAS_INCOME"
          NO PROPERTIES,
        "DEMO"."RESIDENTS_SUB2" SOURCE "RESIDENT", DESTINATION "EXPENSE"
          LABEL "HAS_EXPENSE"
          NO PROPERTIES,
        "DEMO"."RESIDENTS_SUB3" SOURCE "EXPENSE", DESTINATION "EXPENSE_DETAIL"
          LABEL "HAS_DETAIL"
          NO PROPERTIES)

########
Only if a WHERE clause is actually needed, CAREFULLY check if any string in the question is in DOUBLE QUOTES, and follow the rules: 
 - If a string is in DOUBLE QUOTES, use case SENSITIVE comparisons with NO UPPER() function.
 - If a string is not in DOUBLE QUOTES, use case INSENSITIVE comparisons by using UPPER() function around both operands of the string comparison.
Do not add a WHERE clause unless the user explicitly asks for a filter or a filter is required to answer the question.
Do not invent placeholder string comparisons or arbitrary predicates.

Question: 支出に占める食費の割合が一番高い住民の名前とパーセンテージを教えて

LLM がプロパティ・グラフを理解できるように様々な説明を施した後に、実際のグラフの DDL を記載しています。
さらに、

--'住民の収入・支出・支出明細を表すグラフ。
RESIDENTは住民、INCOMEは収入、EXPENSEは支出、
EXPENSE_DETAILは支出明細。
HAS_EXPENSEは住民と支出、
HAS_EXPENSE_DETAILSは支出と各明細を結ぶ。
HAS_EXPENSE_DETAILSのKINDの値には 食費 と その他 の値が含まれる。'

のような説明が入れてあることにはちょっと驚きました。

プロパティ・グラフを使った Select AI の効用とは?

では、リレーショナル・テーブルでも精度を向上させることはできないかというと、プロンプトを工夫すればできます。

image.png
結果
image.png

より精度の高い回答を得るためには、追加的なコンテキストをプロンプトに挿入する訳ですが、プロパティ・グラフに対する Select AIであれば、グラフ構造に基づいたコンテキストが裏側で付加されるため、特別な仕組みを考えなくても自然言語で精度の高い自然言語での問い合わせができます。

まとめ

Select AI の回答精度に課題が残る場合は、データ間の関係をどう伝えるかを見直すことも有効です。特に、複数のテーブルにまたがる関係をたどる質問では、プロパティ・グラフの活用を試してみてはいかがでしょうか。

「リレーショナル・テーブルを土台にしてプロパティ・グラフを作成し Select AI の精度を高める」... まさに コンバージド・データベース(Converged Database) だからこそできることです。

今回 Select AI for Python を使ってみました。PL/SQL のパッケージを触らずに Python 環境で Select AI を扱えるのは嬉しいですね!

11
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?