XML in Datenbanken XQuery und eXist

Transcrição

XML in Datenbanken XQuery und eXist
XML in Datenbanken
XQuery und eXist
10a
G. Görz, J. Schneeberger
Lehrstuhl Informatik 8 (KI)
[email protected]
[email protected]
1
Literatur
• Anders Møller & Michael I. Schwartzbach,
2006 Addison-Wesley
2
XQuery
3
Datenbanken und Relationen
• Unter einer Datenbank (DB) verstehen
Informatiker (fast immer) eine „relationale“
Datenbank.
• Eine relationale Datenbank besteht aus
– Relationen (= Tabellen)
– und Einträgen (Records, Tupel) in diesen
Relationen
• Jeder Eintrag einer Tabelle wird durch einen
eindeutigen Schlüssel markiert.
4
Tabelle/Relation vs. Baum
5
Bäume sind keine Relationen
• Bäume, die Relationen entsprechen,
– haben die feste Tiefe 2
– haben eine beliebige Anzahl von Kinderknoten,
deren Reihenfolge nicht relevant ist (kann beliebig
umgeordnet werden)
– alle Knoten der untersten Ebene haben die selbe Anzahl
und Struktur von Kindern (Spalten können beliebig
umgeordnet werden)
• Die meisten Bäume entsprechen nicht dieser
Spezifikation.
– Äste in Bäumen sind geordnet
– Es können sich beliebige unterschiedliche Teilbäume an
einem Knoten befinden.
6
Eine Beispiel Datenbank
7
In
XML
...
8
<students>
<student id="100026">
<name>Joe Average</name>
<age>21</age>
<major>Biology</major>
<results>
<result course="Math 101" grade="C-"/>
<result course="Biology 101" grade="C+"/>
<result course="Statistics 101" grade="D"/>
</results>
</student>
<student id="100078">
<name>Jack Doe</name>
<age>18</age>
<major>Physics</major>
<major>XML Science</major>
<results>
<result course="Math 101" grade="A"/>
<result course="XML 101" grade="A-"/>
<result course="Physics 101" grade="B+"/>
<result course="XML 102" grade="A"/>
</results>
</student>
</students>
Vorteile von Datenbanken
• Transaktionierung von Operationen
• Steuerung der Zugriffsberechtigungen
• Informationsextraktion durch Anfragen
– SQL = structured query language
• Die Anfragemöglichkeit soll auch für XMLDaten bereit gestellt werden.
– Warum reicht XPath nicht?
9
Warum Anfragen?
•
•
•
•
Um Teile eines Dokuments zu extrahieren
Um einen dynamischen Index zu erzeugen
Zur kontextabhängigen Suche
Zur Erzeugung neuer Dokumente aus einer
Kombination bestehender
• Zur automatischen Generierung von
Dokumenten
• Um Informationen zu kombinieren
• Zur Suche nach Auffälligkeiten in den Teilen
10
XQuery Design Anforderungen
• Must have at least one XML syntax and at least
one human-readable syntax
• Must be declarative
• Must be namespace aware
• Must coordinate with XML Schema
• Must support simple and complex datatypes
• Must combine information from multiple
documents
• Must be able to transform and create XML trees
11
[http://www.w3.org/TR/xquery-requirements/]
XQuery und XPath
• XQuery 1.0 ist eine echte Obermenge von
XPath 2.0
• Jeder XPath 2.0-Ausdruck ist ebenfalls ein
XQuery 1.0-Ausdruck (Query)
• XQuery 1.0 kann zusätzlich:
– Informationen aus verschiedenen Quellen
verbinden
– neue XML-Fragmente erzeugen
12
XQuery und XSLT
• XQuery und XSLT sind beides spezielle
Sprachen, um XML Daten aus unterschiedlichen
Quellen zu kombinieren
• XQuery und XSLT sind sehr unterschiedlich im
Design (aus historischen Gründen)
• XQuery wurde mit SQL als Vorbild entworfen.
• XSLT wurde als Alternative zu CSS entworfen.
• Aus einer technischen Sicht kann XSLT wohl
XQuery emulieren und umgekehrt.
13
XSLT und XQuery
XSLT 2.0
XQuery 1.0
Functions
and
Operators
XPath 2.0
Data Model
XML Schema
[M. Kay]
14
XSLT und XQuery
XQuery 1.0
XSLT 2.0
XPath 2.0
XSLT 1.0
XPath 1.0
XML Schema
15
Die Sprache XQuery
16
Übersicht
• Deklarationen
• Datentypen
• XQuery Ausdrücke
– Konstruktoren
– FLWOR
– Funktionen
• Beispiel
17
Xquery-Prolog
• Xquery-Ausdrücke werden relativ zu einem
Kontext evaluiert (wie XPath).
• Der Kontext wird explizit durch den Prolog
vorgegeben.
• Dabei werden verschiedene Parameter für
den Xquery-Prozessor spezifiziert.
18
xquery version "1.0";
declare xmlspace preserve;
declare xmlspace strip;
declare default element namespace URI;
declare default function namespace URI;
import schema at URI;
declare namespace NCName = URI;
Implizite Deklarationen
declare namespace xml = "http://www.w3.org/XML/1998/namespace";
declare namespace xs = "http://www.w3.org/2001/XMLSchema";
declare namespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
declare namespace fn = "http://www.w3.org/2005/11/xpath-functions";
declare namespace xdt = "http://www.w3.org/2005/11/xpath-datatypes";
declare namespace local ="http://www.w3.org/2005/11/xquery-local-functions";
19
Xpath-Ausdrücke
• Xpath-Ausdrücke sind auch XqueryAusdrücke.
• Der Xquery-Prolog spezifiziert den
notwendigen Xpath-Kontext.
• Der initiale Kontext, Position (position) und
Umfang (size) sind undefiniert.
20
Atomare Werte und primitive
Datentypen
• Dieselben atomaren Werte wie in XPath 2.0
• Viele Primitive
21
xs:string("XML is fun")
xs:boolean("true")
xs:decimal("3.1415")
xs:float("6.02214199E23")
xs:dateTime("1999-05-31T13:20:00-05:00")
xs:time("13:20:00-05:00")
xs:date("1999-05-31")
xs:gYearMonth("1999-05")
xs:gYear("1999")
xs:hexBinary("48656c6c6f0a")
xs:base64Binary("SGVsbG8K")
xs:anyURI("http://www.brics.dk/ixwt/")
xs:QName("rcp:recipe")
Datentypen
• Atomare Werte
– Instanzen eines
einfachen Typs
– XQuery besitzt
eigene und von XML
Schema vererbte
Datentypen
– Beispiele
•
•
•
•
•
xs:integer
xs:string
xs:date
xs:boolean
xdt:untypedAtomic
22
[Markus Mauch: http://www.ipd.uni-karlsruhe.de/~oosem/S2D2/]
Datentypen
• Knoten
– XML-Dokument:
Baum bestehend aus
Knoten
– Knotentypen
•
•
•
•
•
•
•
element
attribute
text
document-node
comment
processing-instruction
namespace
– Elementknoten
• Einfacher und
komplexer Inhalt
• Textueller Wert und Typ
23
<?xml version="1.0"?>
<greetings>
<!-- Welcome Message -->
<welcome>
Hello XQuery World
</welcome>
</greetings>
[Markus Mauch: http://www.ipd.uni-karlsruhe.de/~oosem/S2D2/]
Xquery-Ausdrücke
• Xquery-Ausdrücke können neue XML-Knoten
erzeugen.
• Xquery-Ausdrücke können beschreiben:
–
–
–
–
Elemente
Character data
Kommentare
Processing instructions
• Jeder Knoten wird mit einer eindeutigen Id
erzeugt.
• Konstruktoren sind entweder direkt (direct) oder
berechnet (computed)
24
Direkte Konstruktoren
• Verwenden Standard-XML-Syntax
• Der Ausdruck
<foo><bar/>baz</foo>
erzeugt das entsprechende XML-Fragment.
• Der Ausdruck
<foo/> is <foo/>
ist false.
25
Namensräume in Konstruktoren
declare default element namespace "http://businesscard.org";
<card>
<name>John Doe</name>
<title>CEO, Widget Inc.</title>
<email>[email protected]</email>
<phone>(202) 555-1414</phone>
declare namespace b = "http://businesscard.org";
<logo uri="widget.gif"/>
<b:card>
</card>
<b:name>John Doe</b:name>
<b:title>CEO, Widget Inc.</b:title>
<b:email>[email protected]</b:email>
<b:phone>(202) 555-1414</b:phone>
<b:logo uri="widget.gif"/>
<card xmlns="http://businesscard.org">
</b:card>
<name>John Doe</name>
<title>CEO, Widget Inc.</title>
<email>[email protected]</email>
<phone>(202) 555-1414</phone>
<logo uri="widget.gif"/>
26
</card>
Eingebettete Ausdrücke
<foo>1 2 3 4 5</foo>
<foo>{1, 2, 3, 4, 5}</foo>
<foo>{1, "2", 3, 4, 5}</foo>
<foo>{1 to 5}</foo>
<foo>1 {1+1} {" "} {"3"} {" "} {4 to 5}</foo>
<foo bar="1 2 3 4 5"/>
<foo bar="{1, 2, 3, 4, 5}"/>
<foo bar="1 {2 to 4} 5"/>
27
Explizite Konstruktoren
<card xmlns="http://businesscard.org">
<name>John Doe</name>
<title>CEO, Widget Inc.</title>
<email>[email protected]</email>
<phone>(202) 555-1414</phone>
<logo uri="widget.gif"/>
</card>
28
element card {
namespace { "http://businesscard.org" },
element name { text { "John Doe" } },
element title { text { "CEO, Widget Inc." } } ,
element email { text { "[email protected]" } },
element phone { text { "(202) 555-1414" } },
element logo {
attribute uri { "widget.gif" }
}
}
Berechnete Tag-Namen (QNames)
element { "card" } {
namespace { "http://businesscard.org" },
element { "name" } { text { "John Doe" } },
element { "title" } { text { "CEO, Widget Inc." } },
element { "email" } { text { "[email protected]" } },
element { "phone" } { text { "(202) 555-1414" } },
element { "logo" } {
attribute { "uri" } { "widget.gif" }
}
}
29
Berechnete Tag-Namen (QNames)
element { if ($lang="Danish") then "kort" else "card" } {
namespace { "http://businesscard.org" },
element { if ($lang="Danish") then "navn" else "name" }
{ text { "John Doe" } },
element { if ($lang="Danish") then "titel" else "title" }
{ text { "CEO, Widget Inc." } },
element { "email" }
{ text { "[email protected]" } },
element { if ($lang="Danish") then "telefon" else "phone"}
{ text { "(202) 456-1414" } },
element { "logo" } {
attribute { "uri" } { "widget.gif" }
}
}
30
FLWORAusdrücke
• Allgemeine Xquery-Anfragen
• for – let – where – order- return (FLWOR)
<doubles>
{ for $s in fn:doc("students.xml")//student
let $m := $s/major
where fn:count($m) ge 2
order by $s/@id
return <double>
{ $s/name/text() }
</double>
}
</doubles>
31
for und let (1/4)
for $x in (1, 2, 3, 4)
let $y := ("a", "b", "c")
return ($x, $y)
1, a, b, c, 2, a, b, c, 3, a, b, c, 4, a, b, c
32
for und let (2/4)
let $x in (1, 2, 3, 4)
for $y := ("a", "b", "c")
return ($x, $y)
1, 2, 3, 4, a, 1, 2, 3, 4, b, 1, 2, 3, 4, c
33
for und let (3/4)
for $x in (1, 2, 3, 4)
for $y := ("a", "b", "c")
return ($x, $y)
1, a, 1, b, 1, c, 2, a, 2, b, 2, c,
3, a, 3, b, 3, c, 4, a, 4, b, 4, c
34
for und let (4/4)
let $x in (1, 2, 3, 4)
let $y := ("a", "b", "c")
return ($x, $y)
1, 2, 3, 4, a, b, c
35
Joins
declare namespace rcp = "http://www.brics.dk/ixwt/recipes";
for $r in fn:doc("recipes.xml")//rcp:recipe
for $i in $r//rcp:ingredient/@name
for $s in fn:doc("fridge.xml")//stuff[text()=$i]
return $r/rcp:title/text()
<fridge>
<stuff>eggs</stuff>
<stuff>olive oil</stuff>
<stuff>ketchup</stuff>
<stuff>unrecognizable moldy thing</stuff>
</fridge>
<recipes xmlns:rcp="...">
<rcp:recipe>
<rcp:ingredient>egg</rcp:ingredient>
<rcp:ingredient>butter</rcp:ingredient>
</rcp:recipe>
:
36
</recipes>
Invertierte Relation
declare namespace rcp = "http://www.brics.dk/ixwt/recipes";
<ingredients>
{ for $i in distinct-values(
fn:doc("recipes.xml")//rcp:ingredient/@name
)
return <ingredient name="{$i}">
{ for $r in fn:doc("recipes.xml")//rcp:recipe
where $r//rcp:ingredient[@name=$i]
return <title>$r/rcp:title/text()</title>
}
</ingredient>
}
</ingredients>
37
Sortieren der Ergebnisse
declare namespace rcp = "http://www.brics.dk/ixwt/recipes";
<ingredients>
{ for $i in distinct-values(
fn:doc("recipes.xml")//rcp:ingredient/@name
)
order by $i
return <ingredient name="{$i}">
{ for $r in fn:doc("recipes.xml")//rcp:recipe
where $r//rcp:ingredient[@name=$i]
order by $r/rcp:title/text()
return <title>$r/rcp:title/text()</title>
}
</ingredient>
}
</ingredients>
38
Komplizierteres Sortieren
for $s in document("students.xml")//student
order by
fn:count($s/results/result[fn:contains(@grade,"A")]) descending,
fn:count($s/major) descending,
xs:integer($s/age/text()) ascending
return $s/name/text()
39
Funktionen
declare function local:grade($g) {
if ($g="A") then 4.0 else if ($g="A-") then 3.7
else if ($g="B+") then 3.3 else if ($g="B") then
else if ($g="B-") then 2.7 else if ($g="C+") then
else if ($g="C") then 2.0 else if ($g="C-") then
else if ($g="D+") then 1.3 else if ($g="D") then
else if ($g="D-") then 0.7 else 0
};
3.0
2.3
1.7
1.0
declare function local:gpa($s) {
fn:avg(for $g in $s/results/result/@grade
return local:grade($g))
};
40
<gpas>
{ for $s in fn:doc("students.xml")//student
return <gpa id="{$s/@id}" gpa="{local:gpa($s)}"/> }
</gpas>
Typisierte und untypisierte Funktionen
41
Sequenz-Typen
2 instance of xs:integer
2 instance of item()
2 instance of xs:integer?
() instance of empty()
() instance of xs:integer*
(1,2,3,4) instance of xs:integer*
(1,2,3,4) instance of xs:integer+
<foo/> instance of item()
<foo/> instance of node()
<foo/> instance of element()
<foo/> instance of element(foo)
<foo bar="baz"/> instance of element(foo)
<foo bar="baz"/>/@bar instance of attribute()
<foo bar="baz"/>/@bar instance of attribute(bar)
fn:doc("recipes.xml")//rcp:ingredient instance of element()+
fn:doc("recipes.xml")//rcp:ingredient
instance of element(rcp:ingredient)+
42
XML und Datenbanken
• Wie können XML und Datenbanken
verbunden werden?
• Ansätze:
– Extraktion von XML (views) für Relationen
– Verwendung von SQL, um XML zu erzeugen
– „shred XML into relational databases”
43
Automatische XML-Erzeugung
44
Automatische XML-Erzeugung
45
Automatische XML-Erzeugung
46
Automatische XML Erzeugung
47
XML schreddern
• Jedes Element wird durch eine Relation
dargestellt
• Jeder Element-Knoten erhält eine eindeutige Id
• Jeder Element Knoten verweist auf seinen
Elternknoten
• Die möglichen Attribute werden als Felder (der
Relation) dargestellt. Abwesende Felder haben
den Wert null.
• Knoteninhalte, die nur aus Zeichen bestehen
werden als Felder dargestellt.
48
XQuery Processing Model
! Formalized & normative:
– Normalization of expressions into
a smaller “core” grammar (SQ5)
– Static typing (SQ6)
! Formalized & non-normative:
– Dynamic evalution (DQ1)
! Formalized & informative:
– Schema import (SI1)
49
[Jerome Simeon]
eXist
50
Quellen
• Chris Wallace, University of the West of
England, Bristol, UK
• Yin-Fu Huang, Shing-Hang Wang
51
Why not an RDBMS?
• Documents
–
–
–
–
Unit of editing, ownership, communication
Complex composite structures
Ordering and other complex relationships
Linked by shared values
52
eXist Native XML Database
•
•
•
Open source Java
European team of developers led by Wolfgang Meier(Darmstadt)
Documents (files) are organised in collections (folders) in a file store
– XML Documents stored in an efficient, B+ tree structure with indexes
– Non-XML resources (XQuery, CSS, JPEG ..), etc can be stored as binary
•
Deployable in different ways
– Embedded in a Java application
– With embedded Jetty HTTPserver
•
Multiple Interfaces
– REST – to Java servlet
– SOAP
– XML:RPC
•
Support for XQuery
–
–
–
–
Function library extensions
Language extensions (free-text matching and update)
Schema validation supported
Database is not schema-aware – no type information available
53
Architecture Overview
54
Database Features
• Data Storage
– Native XML data store based on B+-trees and paged
files. Document nodes are stored in a DOM tree.
• Collections
– Documents are managed in hierarchical collections,
similar to storing files in a file system
• Updates
– Document-level and node-level updates.
• Authorization Mechanism
– Unix-like access permissions for users/groups at
collection- and document-level.
55
Database Features
•
Multi-User Access
– Concurrent read/write access supported. Database manages
concurrency at the level of the basic database operations.
•
Deployment
– eXist may be deployed as a stand-alone database server, as an
embedded Java library or as part of a web application (running in the
servlet engine).
•
Backup/Restore
– Backup/restore functionality is provided via Java admin client or Ant
scripts. Allows full restore of a database including user/group
permissions.
•
XML Standards
– XPath, Xquery, XUpdate, XSL/XSLT.
•
Network Protocols
– HTTP/REST, XML-RPC, SOAP, WebDAV
56
Numbering Schemes
• The major benefit of Numbering Schemes is that
relationships can be determined efficient.
• K-ary Tree
57
Numbering Schemes
• Instead the number of children a node may have is
recomputed for every level of the tree.
– Two nodes x and y of a tree, size(x) = size(y) if level(x) = level(y)
58
Index and Data Organization
• eXist uses four index files at the core of the native XML
storage backend:
– collections.dbx - manages the collection hierarchy
– dom.dbx - collects nodes in a paged file and associates unique
node identifiers to the actual nodes
– elements.dbx - indexes elements and attributes
– words.dbx - keeps track of word occurrences and is used by the
fulltext search extensions
• All based on B+-trees
59
collections.dbx
•
•
Manages the collection hierarchy and maps collection names to
collection objects.
An important point to note is that the indexes for elements,
attributes and keywords are organized by collection and no by
document
XML
collection
collection
collection
XML
60
dom.dbx
•
•
The XML data store(dom.dbx) represents the central component
of eXist's native storage architecture.
All document nodes are stored according to the W3C's DOM
(Document Object Model).
•
The data store is backed by a multi-root B+-Tree in the same
file.
•
Associate the unique node identifiers of top-level elements in a
given document to the node’s storage address in the data
pages.
61
dom.dbx
•
However, the query engine will process most types of XPath
without accessing dom.dbx.
62
elements.dbx
•
•
•
Element and Attribute names are mapped to unique node identifiers
in file elements.dbx.
Each entry in the B+-tree index consists of a key <collection-id, name-id>
And each key correspond an array containing an list of
<document-id, node-id>
Attribute or
Element
63
word.dbx
•
•
•
words.dbx corresponds to an inverted index as found. with the set of
documents in which it has been found and the exact position where it
occurred
Using <collection-id, keyword> pair for key, like element.dbx
Each entry in the value list points to a text or attribute node where the
keyword occurred.
<collection-id,
keyword>
Keyword occurred
Keyword occurred
Like node-id
64
Query Language Implementation
•
First decompose a given path expression into a chain of basic steps
•
Example Query
– /PLAY//SPEECH[SPEAKER=’HAMLET’]
• <1> Load the root elements "PLAY" for all documents in the input document
set.
• <2> The set of "SPEECH" element is retrieved for the input documents via an
index lookup from file elements.dbx.
• <3> Ancestor-descendant join algorithm is applied to the two sets (use
<document-id, node-id>). And repeat.
• <4> While value need to be compared (like "HAMLET”), it must retrieved
value from dom.dbx.
65
Fulltext Search
• The fulltext index is required by eXist's fulltext
extensions.
• "|=" operators.
– node-set |= 'string of keywords'
• selects context nodes containing any of the keywords in
the right-hand argument.
• The fulltext index is stored in file words.dbx.
66
Performance
XPath Query
eXist
eXist+
extensions
/movie[.//genre='Drama']//credit[@role='directors']
3.44
1.14
/movie[genres/genre='Western']/title
0.79
/movie[languages/language='English']/title
1.45
/movie[.//credit/@charactername='Receptionist']
3.12
/movie[contains(.//comment, 'predictable')]
/movie[.//credit='Gable, Clark']
Xindice
Jaxen
10.62
21.86
0.23
1.39
7.58
0.97
34.18
8.5
0.21
27.04
51.48
2.79
0.2
25.75
31.49
4.47
0.35
0.38
33.72
/movie[.//languages/language='English']/title[starts-with(.,'42nd Street')]
1.63
0.32
17.47
32.64
/movie[languages/language='English' and cred-its/credit='Sinatra, Frank']
5.16
0.58
0.11
13.26
19.07.2011
MM & DB Lab.
67

Documentos relacionados