mysql spatial
Post on 05-Dec-2014
2.060 Views
Preview:
DESCRIPTION
TRANSCRIPT
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 1
Airton Lastori airton.lastori@oracle.com
10-abr-2013
MySQL Spatial
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 2
@MySQLBR
meetup.com/MySQL-BR
facebook.com/MySQLBR
MySQLBR
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 3
Alguns clientes MySQL
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 4
Alguns clientes MySQL
fonte: alexa.com/topsites 30-jan-2013
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 5
Alguns clientes MySQL
mysql.com/customers
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 6
Alguns clientes MySQL
mysql.com/customers
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 7
MySQL: casos de sucesso
+ de 20 indústrias
mysql.com/customers
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 9
2008
até 4 CPU
MySQL 5.0
MySQL AB
até 16 CPU
MySQL 5.1
Sun
até 32 CPU
MySQL 5.5
Oracle
até 48 CPU
MySQL 5.6
Evolução da escalabilidade do MySQL
2009 2010 2013
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 10
MySQL Database Community Server
MySQL Cluster
MySQL Workbench
MySQL Connectors
MySQL Proxy
Documentação não GPL
Forums, Lists, Bugs, Blogs…
Compromisso Oracle com MySQL Community Portfólio disponível para download e uso sob GPL
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 11
Conectores: amplo suporte a várias linguagens
Oracle
• Connector/ODBC
• Connector/Net (ADO.NET)
• Connector/Python
• Connector/J (JDBC)
• Connector/C (C API)
• Connector/C++ (C++ API)
Comunidade
• PHP
• Perl
• Ruby
• TCL
• Eiffel
• …
dev.mysql.com/doc/refman/5.5/en/connectors-apis.html
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 12
Oracle Premier Lifetime Support
Oracle Product Certifications/Integrations
MySQL Enterprise High Availability
MySQL Enterprise Security
MySQL Enterprise Scalability
MySQL Enterprise Backup
MySQL Enterprise Monitor/Query Analyzer
MySQL Workbench
MySQL Enterprise Edition Maior produtividade e mitigação de riscos
MySQL Enterprise Audit
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 13
Suporte às mais
conhecidas
plataformas/linguagens
de desenvolvimento Gerenciamento
eficiente e multi-
thread de sessões Parsing completo
DML+DDL,
otimizador,
baseado em custo,
caching de queries
e resultados
Várias opções de
Storage Engine
para necessidades
específicas das
aplicações
Opções flexíveis de
logging e
armazenamento
físico
Arquitetura MySQL Database
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 14
Qual Storage Engine usar?
MyISAM InnoDB Archive NDB Cluster
Transações ✖ ✔ ✖ ✔
Nível de Lock Tabela Linha Tabela Linha
Replicação Assíncrona ou
Semi-síncrona
Assíncrona ou
Semi-síncrona
Assíncrona ou
Semi-síncrona
Síncrona, Multi-
master
Foreign Keys ✖ ✔ ✖ a partir da v7.3
Full-text indexes ✔ a partir da v5.6 ✖ ✖
Compressão de dados somente Leitura ✔ ✔ ✖
Caches somente Índices Dados e Índices ✖ Dados e Índices
Suporte Geospacial Tipos de Dados e
Índices
somente Tipos de
Dados
somente Tipos de
Dados
somente Tipos de
Dados
Limite de
armazenamento 256TB 64TB Ilimitado 384EB
dev.mysql.com/doc/refman/5.5/en/storage-engines.html
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 15
MySQL Spatial Extensions
Suporte à geração,
armazenamento e análise de
informações geográficas.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 16
Modelo conceitual para dados espaciais / geográficos
propõe extensões para SGBDs SQL
padronizado pelo Open Geospatial Consortium
inclui SQL with Geometry Types, estendendo a linguagem
MySQL é aderente ao OpenGIS
implementa um subconjunto dos SQL with Geometry Types
colunas podem possuir os Tipos Geométricos do OpenGIS
também estão disponíveis funções geométricas para análise
OpenGIS Simple Features Specification for SQL
www.opengis.org/docs/99-049.pdf
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 17
geographic feature ou geospatial feature ou geometry
algo com uma localização no mundo
definido e representado por um ponto ou agregado de pontos
pode ser uma entity, space, definable location
entity
uma montanha, um lago, uma cidade etc
space
um distrito municipal, os trópicos etc
definable location
um cruzamento entre ruas, etc
Terminologia OpenGIS Simple Features Specification for SQL
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 18
OpenGIS Geometry Model Tipos de Dados propostos no SQL with Geometry Types
*apenas tipos em negrito podem ser instanciados
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 19
OpenGIS Geometry Model Exemplos de utilização dos Tipos de Dados instanciáveis
Point Em um mapa mundi, cada Point poderia representar uma cidade.
Em um mapa municipal, Points representariam paradas de ônibus.
Linestring Em um mapa mundi, poderia representar rios.
Em um mapa municipal, poderia representar ruas.
Polygon Em um mapa nacional, poderia representar florestas, estados etc.
MultiPoint Em um mapa mundi, poderia representar uma cadeia de pequenas ilhas
que formam um arquipélogo.
Em um mapa municipal, poderia representar pontos de paradas de uma
linha de ônibus.
MultiLineString Em um mapa nacional, poderia representar rodovias federais ou rios
conectados.
MultiPolygon Em um mapa nacional, poderia representar lagos pertencentes ao mesmo
sistema hídrico.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 20
OpenGIS Geometry Model Hierarquia das Propriedades – Geometry e Point
Geometry
type
SRID
coordinates
interior
boundary
exterior
MBR //envelope
simple
closed
empty
dimension
Point
x-coordinate
y-coordinate
dimension = 0
boundary = EMPTY
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 21
WKT (Well-Known Text Format)
projetado para transportar dados em ASCII, fácil leitura, por exemplo:
POINT(15 20)
LINESTRING(0 0, 10 10, 20 25, 50 60)
POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))
WKB (Well-Known Binary Format) OpenGIS e ISO SQL/MM Part 3 Spatial
BLOBs contendo dados binários de informações geométricas WKB
POINT(1 1) = 0101000000000000000000F03F000000000000F03F
1 byte (unsigned) para endianess
4 bytes (unsigned) para Tipo de Dado de 1 a 7
8 bytes (double-precision IEEE 754) para coordenadas X e Y
OpenGIS Geometry Model Formatos de Armazenamento
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 22
Criando um BD MySQL Spatial Tipos de Dados disponíveis
GEOMETRY pode armazenar geometrias de qualquer tipo
POINT
LINESTRING
POLYGON
GEOMETRYCOLLECTION pode armazenar coleções de todos tipos
MULTIPOINT
MULTILINESTRING
MULTIPOLYGON
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 23
Criando um BD MySQL Spatial Exemplo: criando uma tabela
CREATE TABLE mapamundi (
cidade POINT ) ENGINE=MyISAM;
mapamundi
cidade
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 24
Criando um BD MySQL Spatial Exemplo: alterando uma tabela, adicionar coluna
ALTER TABLE mapamundi
ADD rio LINESTRING;
mapamundi
cidade rio
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 25
Criando um BD MySQL Spatial Exemplo: alterando uma tabela, remover colunas
ALTER TABLE mapamundi DROP rio;
ALTER TABLE mapamundi
ADD geometria GEOMETRY;
ALTER TABLE mapamundi DROP cidade;
mapamundi
geometria
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 26
Criando um BD MySQL Spatial Criando objetos com funções WKT
GeomFromText() ou
funções específicas para cada Tipo, ex: PointFromText()
Criando objetos com funções WKB
GeomFromWKB() ou
funções específicas para cada Tipo, ex: PointFromWKB()
Criando objetos com funções específicas do MySQL
Point(), LineString(), Polygon()
GeometryCollection(), MultiPoint(), MultiLineString(), MultiPolygon()
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 27
Criando um BD MySQL Spatial Exemplo: inserindo um Point via WKT
INSERT INTO mapamundi VALUES (
GeomFromText('POINT(1 1)')
);
INSERT INTO mapamundi VALUES(
Point(1,1)
);
ou também…
mapamundi
geometria
1 POINT(1 1)
SET @g = 'POINT(1 1)';
INSERT INTO mapamundi VALUES (
GeomFromText(@g)
);
...ou ainda…
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 28
Criando um BD MySQL Spatial Exemplo: removendo um Point
DELETE FROM mapamundi
WHERE geometria = GeomFromText('POINT(1 1)');
mapamundi
geometria
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 29
Criando um BD MySQL Spatial Exemplo: inserindo um Point via WKB
INSERT INTO mapamundi VALUES (
GeomFromWKB(0x0101000000000000000000F03F000000000000F03F)
);
mapamundi
geometria
1 POINT(1 1)
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 30
Criando um BD MySQL Spatial Exemplo: inserindo um LineString
mapamundi
geometria
1 POINT(1 1)
2 LINESTRING(0 0,1 1,2 2)
SET @g = 'LINESTRING(0 0,1 1,2 2)';
INSERT INTO mapamundi VALUES (
GeomFromText(@g)
); SET @g = ‘LINESTRING(0 0,1 1,2 2)';
INSERT INTO mapamundi VALUES (
LineStringFromText(@g)
);
ou também…
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 31
Criando um BD MySQL Spatial Exemplo: inserindo um Polygon
mapamundi
geometria
1 POINT(1 1)
2 LINESTRING(0 0,1 1,2 2)
3 POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))
SET @g = 'POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))';
INSERT INTO mapamundi VALUES (GeomFromText(@g));
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 32
Criando um BD MySQL Spatial Exemplo: consultando registros
mapamundi
geometria
1 POINT(1 1)
2 LINESTRING(0 0,1 1,2 2)
3 POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))
SELECT AsText(geometria) FROM mapamundi;
SELECT AsBinary(geometria) FROM mapamundi;
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 33
Análise de dados com MySQL Spatial Funções Disponíveis 1/2
Conversão
AsBinary(), AsText(), GeomFromText(), GeomFromWKB()
Propriedades
Dimension(), Envelope(), GeometryType(), IsSimple(), SRID()
X(), Y()
EndPoint(), GLenght(), NumPoints(), PointN(), StartPoint()
IsClosed()
Area(), ExteriorRing(), InteriorRingN(), NumInteriorRings()
Centroid()
GeometryN(), NumGeometries()
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 34
Análise de dados com MySQL Spatial Funções Disponíveis 2/2
Relações
MBRContains(), MBRDisjoint(), MBREqual(), MBRIntersects(), MBROverlaps(), MBRTouches(), MBRWithin()
Contains(), Crosses(), Disjoint(), Equals(), Intersects(), Overlaps(), Touches(), Within()
ST_Contains(), ST_Crosses(), ST_Disjoint(), ST_Equals(), ST_Intersects(), ST_Overlaps(), ST_Touches, ST_Within()
Clonagem
Buffer()
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 35
Otimizações nos dados do MySQL Spatial Índices SPATIAL para Range Scans
Criando Índices Spatial
ALTER TABLE mapamundi CHANGE geometria geometria GEOMETRY NOT NULL;
CREATE SPATIAL INDEX sp_index ON mapamundi(geometria);
Usando Índices Spatial em Range Scans
SET @g = 'POLYGON((0 0,9 0,9 9,0 9,0 0),(5 5,7 5,7 7,5 7, 5 5))';
SELECT AsText(geometria) FROM mapamundi
WHERE MBRContains(GeomFromText(@g),geometria);
…apenas deixe o trabalho de selecionar o índice para o Optimizer!
Use o comando EXPLAIN para confirmar se o índice é utilizado.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 36
Nível de Conformidade do MySQL Spatial com
OpenGIS Funcionalidades não-padronizadas
Lenght() implementada com o nome GLenght()
Funcionalidades adicionais
próximos slides
Funcionalidades não-implementadas
próximos slides
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 37
GeometryCollection(g1,g2,...)
LineString(pt1,pt2,...)
MultiLineString(ls1,ls2,...)
MultiPoint(pt1,pt2,...)
MultiPolygon(poly1,poly2,...)
Point(x,y)
Polygon(ls1,ls2,...)
Funcionalidades Adicionais do MySQL Spatial não
definidas pelo OpenGIS
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 38
Funcionalidades definidas pelo OpenGIS e não
implementadas pelo MySQL BdPolyFromText() e BdMPolyFromText()
BdPolyFromWKB() e BdMPolyFromWKB()
Boundary()
Buffer() implementada a partir do MySQL 5.6
ConvexHull()
Difference()
Intersection()
IsEmpty() e IsRing()
IsSimple() implementada a partir do MySQL 5.6
PointOnSurface()
SymDifference()
Union
Metadata Views como GEOMETRY_COLUMNS
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 39
Como começar
Instalação básica, ambiente de
desenvolvimento…
...em 15 minutos, ou menos!
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 40
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 41
mysql.com/downloads/mysql
No Linux ou Mac, prefira os binários
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 42
Client mysql / mysql.exe
Server mysqld / mysqld.exe
Cliente-Servidor
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 43
Iniciar ou Parar o servidor MySQL no Windows
…ou via MySQL Notifier
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 44
Iniciar ou Parar o servidor MySQL no Linux
/usr/local/mysql/bin> mysqld_safe --defaults-file=/etc/my.cnf &
/usr/local/mysql/bin> mysqladmin shutdown
Parar:
Iniciar:
dev.mysql.com/doc/refman/5.5/en/mysqld-safe.html
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 45
Primeira conexão
C:\Program Files\MySQL\MySQL Server 5.5\bin>mysql -uroot -p
Enter password: ****
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.6.11 MySQL Community Server (GPL)
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 46
Teste via MySQL Workbench 1/2
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 47
Teste via MySQL Workbench 2/2
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 48
App + Connector JDBC, ODBC, .Net, PHP, Python, Perl, Ruby, Native C API…
Server mysqld / mysqld.exe
Cliente-Servidor
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 49
Mãos à obra!
Hello World…
...em Java
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 50
Adicione o driver MySQL ao CLASSPATH caminho completo do .jar
C:\>set CLASSPATH
CLASSPATH=.;C:\Program Files (x86)\Java\jre6\lib\ext\QTJava.zip;C:\Program
Files\MySQL\mysql-connector-java-5.1.22\mysql-connector-java-5.1.22-bin.jar
Confira:
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 51
HelloMysql.java 1/2
import java.sql.*;
public class HelloMysql {
public static void main(String args[]){
System.out.println("Tentando conectar ao MySQL...");
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mysql";
String usuario = "root";
String senha = "root";
Connection con = DriverManager.getConnection(url, usuario, senha);
System.out.println("URL: " + url);
System.out.println("Connection: " + con);
Continua…
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 52
HelloMysql.java 2/2 Statement stmt = con.createStatement(); //objeto Statement
ResultSet rs; //objeto ResultSet
rs = stmt.executeQuery("SELECT * FROM world.country");
System.out.println("Ola mundo!");
while(rs.next()){
String nomePais = rs.getString("Name");
System.out.print(nomePais + ", ");
}//end while
con.close();
} catch( Exception e ) {
e.printStackTrace();
}//end catch
}//end main
}//end class HelloMysql PRONTO!
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 53
java HelloMysql C:\tutorial>javac HelloMysql.java
C:\tutorial>java HelloMysql
Tentando conectar ao MySQL...
URL: jdbc:mysql://localhost:3306/mysql
Connection: com.mysql.jdbc.JDBC4Connection@ed07f45
Ola mundo!
Aruba, Afghanistan, Angola, Anguilla, Albania, Andorra, Netherlands Antilles, Un
ited Arab Emirates, Argentina, Armenia, American Samoa, Antarctica, French South
ern territories, Antigua and Barbuda, Australia, Austria, Azerbaijan, Burundi, B
elgium, Benin, Burkina Faso, Bangladesh, Bulgaria, Bahrain, Bahamas, Bosnia and
Herzegovina, Belarus, Belize, Bermuda, Bolivia, Brazil, Barbados, Brunei, Bhutan
…
ietnam, Vanuatu, Wallis and Futuna, Samoa, Yemen, Yugoslavia, South Africa, Zamb
ia, Zimbabwe,
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 54
Próximo passo: documentação
Reference Manual
1. Tutorial
2. SQL Syntax
3. Connectors & APIs, Memcached
4. MySQL Spatial Extensions
5. Functions, Views, Stored Programs
6. Optimization
dev.mysql.com/doc/refman/5.5/en/index.html
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 55
Sumário
O MySQL é o banco de dados open source mais popular do
mundo, usado em grandes sites, aplicações mobile, embarcadas
e sistemas de informações geográficas.
Possui amplo suporte ao modelo OpenGIS, principalmente no
Storage Engine MyISAM.
Instale e comece a usar em menos de 15min. Use e abuse da
documentação!
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 56
@MySQLBR
meetup.com/MySQL-BR
facebook.com/MySQLBR
Obrigado!
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12 57
Perguntas?
MySQL Spatial
top related