SlideShare une entreprise Scribd logo
1  sur  54
Globalcode – Open4educationGlobalcode – Open4education
Trilha – NoSQL
Caliel Costa
Nerd, ouvinte de blues, pesquisador, esportista e fotógrafo amador, desenvolvedor e projetista de soluções em TI. Software
Designer no Superplayer.
Globalcode – Open4education
Agenda
• Telecurso de Geografia
• Necessidade
• GeoJSON
• Consultas
• Dados
Globalcode – Open4education
Planeta Terra
Globalcode – Open4education
Planeta Terra
Degrees, Minutes, Seconds to/from Decimal Degrees
Cidade Latitude Longitude
Porto Alegre -30.03128
-30° 1' 52.6074" Sul
-51.2125487
51° 12' 45.1764" Oeste
São Paulo -23.598877
-23° 35' 55.9572" Sul
-46.6749596
-46° 40' 29.8554" Oeste
Londres 51.4994438
51° 29' 57.9978" Norte
0
0° 0' 0"
Hong Kong 22.3576782
22° 21' 27.6402" Norte
114.2196956
114° 13' 10.905" Leste
Globalcode – Open4education
Planeta Terra em Polígonos
(21 pontos)
Globalcode – Open4education
Planeta Terra em Polígonos
(84 Pontos)
Globalcode – Open4education
Planeta Terra em Polígonos
(338 Pontos)
Globalcode – Open4education
Superplayer é um serviço de recomendação musical focado em melhorar
todos os momentos da vida das pessoas através da trilha sonora
perfeita.
Startup brasileira
Criado em 2012
Globalcode – Open4education
Web, Android, iOS, Windows Phone, ...
+ 8.500.000
USUÁRIOS ÚNICOS
ACUMULADOS
+ 1.400.000
USUÁRIOS ÚNICOS POR MÊS
+ 4.500.000
VISITAS POR MÊS
Globalcode – Open4education
MongoDB
Na versão 2.4 (em 2013) foi introduzido o suporte a geometrias GeoJSON,
podendo ser usadas em data e consultas.
Globalcode – Open4education
GeoJSON
type coordinates
Point deve ser uma posição simples
MultiPoint deve ser um array de posição
LineString deve ser um array de 2 ou mais posições
MultiLineString deve ser um array de array de LineString
Polygon deve ser um LinearRing, ou seja um LineString com 4 ou mais pontos,
onde o primeiro e o último são posições equivalentes
MultiPolygon deve ser um array de array de Polygon
Globalcode – Open4education
GeoJSON - Point
{
"type": "Point",
"coordinates": [100.0, 0.0],
}
Globalcode – Open4education
GeoJSON - LineString
{
"type": "LineString",
"coordinates": [
[100.0, 0.0],
[101.0, 1.0]
],
}
Globalcode – Open4education
GeoJSON - Polygon
{
"type": "Polygon",
"coordinates": [
[
[100.0, 0.0], [101.0, 0.0],
[101.0, 1.0], [100.0, 1.0],
[100.0, 0.0]
]
],
}
Globalcode – Open4education
GeoJSON - MultiPoint
{
"type": "MultiPoint",
"coordinates": [
[100.0, 0.0],
[101.0, 1.0]
],
}
Globalcode – Open4education
GeoJSON - MutiLineString
{
"type": "MultiLineString",
"coordinates": [
[ [100.0, 0.0], [101.0, 1.0] ],
[ [102.0, 2.0], [103.0, 3.0] ]
]
}
Globalcode – Open4education
GeoJSON - MultiPolygon
{
"type": "MultiPolygon",
"coordinates": [
[
[ [102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0] ]
],
[
[ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ],
[ [100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ]
]
]
}
Globalcode – Open4education
Brazil, seus 27 estados e
respectivas capitais
Globalcode – Open4education
GeoJSON - Brasil
{
"_id" : ObjectId("54f4bd437da3100f4454e812"),
"level" : "Country",
"name" : "Brasil (BR)",
"loc" : {
"type" : "Polygon",
"coordinates" : [
[
[ -44.69501, -1.817778 ],
… 336 ...
[-44.69501, -1.817778 ]
]
]
}
}
Globalcode – Open4education
GeoJSON - Estado São Paulo
{
"_id" : ObjectId("54f4bd5b7da3100f4454e82c"),
"parentid" : "54f4bd437da3100f4454e812",
"level" : "State",
"name" : "São Paulo (SP)",
"loc" : {
"type" : "Polygon",
"coordinates" : [
[
[ -49.3352376, -24.2290424 ],
...497...
[ -49.3352376, -24.2290424 ]
]
]
}
}
Globalcode – Open4education
GeoJSON - Cidade São Paulo
{
"_id" : ObjectId("54f4bd5d7da3100f4454e846"),
"parentid" : "54f4bd5b7da3100f4454e82c",
"level" : "City",
"name" : "São Paulo",
"loc" : {
"type" : "Polygon",
"coordinates" : [
[
[ -46.53766020909132, -23.36963320731797 ],
..310..
[ -46.53766020909132, -23.36963320731797 ]
]
]
}
}
Globalcode – Open4education
Longitude e Latitude Vs
Latitude e Longitude
{
"loc" : {
"type" : "Polygon",
"coordinates" : [
[
[ -46.53766020909132, -23.36963320731797 ],
..310..
[ -46.53766020909132, -23.36963320731797 ]
]
]
}
}
Cidade Latitude Longitude
São Paulo -23.598877
-23° 35' 55.9572" Sul
-46.6749596
-46° 40' 29.8554" Oeste
Globalcode – Open4education
Longitude e Latitude Vs
Latitude e Longitude
“All documents must store location data in the same order. If
you use latitude and longitude as your coordinate system,
always store longitude first. MongoDB’s 2d spherical index
operators only recognize [longitude, latitude] ordering.”
Globalcode – Open4education
Indexando GeoJSON
Tipo Uso
2dsphere Suporta consultas que calculem geometrias em uma esfera tipo a Terra.
2d Gera um geohash de acordo com o valor das coordenadas
haystack Este índice é um tipo especial de índice otimizado para retornar resultados
sobre areas pequenas
Globalcode – Open4education
Indexando GeoJSON
db.locations.createIndex({
"loc" : "2dsphere"
}, {
"name" : "loc_"
})
• Índice esparso
• Não pode ser usado como chave de sharding
Globalcode – Open4education
Consultas GeoJSON
Function Objetivo
$geoWithin Seleciona geometrias dentro dos limites de outra
$geoIntersects Seleciona geometrias em interção com outra
$near Retorna objetos na proximidade de um ponto
$nearSphere Retorna objetos na proximidade de um ponto na esfera
Globalcode – Open4education
Onde estou?
query: {
"loc": {
$geoIntersects: {
$geometry: {
type: "Point" ,
coordinates: [-51.2125487, -30.03128]
}
}
}
}
Globalcode – Open4education
Onde estou?
query: {
"loc": {
$geoIntersects: {
$geometry: {
type: "Point" ,
coordinates: [-51.2125487, -30.03128]
}
}
}
}
Result:
Brasil (BR)
Rio Grande do Sul (RS)
Porto Alegre
Globalcode – Open4education
Onde estou??
query: {
"loc": {
$geoIntersects: {
$geometry: {
type: "Point" ,
coordinates: [-46.6749596, -23.598877]
}
}
}
}
Globalcode – Open4education
Onde estou??
query: {
"loc": {
$geoIntersects: {
$geometry: {
type: "Point" ,
coordinates: [-46.6749596, -23.598877]
}
}
}
}
Result:
Brasil (BR)
São Paulo (SP)
São Paulo
Globalcode – Open4education
Cidades perto de Gramado/RS
{
"level": "City",
"loc": {
$near: {
$geometry: { type: "Point", coordinates: [-50.8586806,-29.3851463] }
$minDistance: 1,
$maxDistance: 300000,
},
}
}
Globalcode – Open4education
Cidades perto de Gramado/RS
{
"level": "City",
"loc": {
$near: {
$geometry: { type: "Point", coordinates: [-50.8586806,-29.3851463] }
$minDistance: 1,
$maxDistance: 300000,
},
}
}
Result:
Porto Alegre
Florianópolis
Globalcode – Open4education
Cidades perto de Campinas/SP
query: {
"level": "City",
"loc": {
$near: {
$geometry: { type: "Point", coordinates: [-47.0562422, -22.9084404] }
$minDistance: 60000,
$maxDistance: 80000,
}
,
}
}
Globalcode – Open4education
Cidades perto de Campinas/SP
query: {
"level": "City",
"loc": {
$near: {
$geometry: { type: "Point", coordinates: [-47.0562422, -22.9084404] }
$minDistance: 60000,
$maxDistance: 80000,
}
,
}
}
Result:
Osasco, Carapicuíba, Cotia, Vargem Grande Paulista
Globalcode – Open4education
$NearSphere
Funciona igual ao Near só que ao invés de se usar
distâncias em metros usa-se em radianos.
Globalcode – Open4education
Playlists
Globalcode – Open4education
Segmentação de Playlists
Globalcode – Open4education
Segmentação de Playlists
Globalcode – Open4education
Segmentação de Playlists
Globalcode – Open4education
Segmentação de Playlists
Playlist
Loc
Type Loc Name
Correndo no Ibira Polygon [ [ [long, lat] … ] ] São Paulo
Rio 40 Graus Polygon [ [ [long, lat] … ] ] Rio de Janeiro
Men’s Health Polygon [ [ [long, lat] … ] ] Brasil (BR)
Globalcode – Open4education
Buscando playlists
query: {
$or: [
{ "location": { $not: { $exists: true } } },
{
"location": {
$geoIntersects: { $geometry: { type: "Point" , coordinates: [-46.6749596, -23.598877] } }
}
}
],
}
Result:
Acorda, Peão!, Acorda, Vagabundo!, Bebendo no Boteco, Correndo no Ibira, Dia de Chuva, Men’s
Health, Trabalhando numa Boa, Whiskynho com a Rapaziada, ...
Globalcode – Open4education
Buscando playlists
query: {
$or: [
{ "location": { $not: { $exists: true } } },
{
"location": {
$geoIntersects: { $geometry: { type: "Point" , coordinates: [-47.0562422, -22.9084404] } }
}
}
],
}
Result:
Acorda, Peão!, Acorda, Vagabundo!, Bebendo no Boteco, Dia de Chuva, Men’s Health, Trabalhando
numa Boa, Whiskynho com a Rapaziada, ...
Globalcode – Open4education
Conteúdo Localizado
• Playlists
• Spots
• Patrocínios de Playlists
• Log de Playlists ouvidas
• Log de Músicas (Tracks) ouvidas
Globalcode – Open4education
Optimização
Play
Mongo
DB
API Web
Play @Rock
Playlist com
tracks
Globalcode – Open4education
Optimização
APIiOS
Play @Rock
MongoD
B
db.locations.find({
"loc": {
$geoIntersects: { $geometry: {
type: "Point" , coordinates: [-46.6749596, -23.598877] }
}
}
}
{ _id: “ABC”, level: “Country”, name: “Brasil (BR)” },
{ _id: “DEF”, level: “State”, name: “São Paulo (SP)” },
{ _id: “GHI”, level: “City”, name: “São Paulo” },
Globalcode – Open4education
Optimização
APIiOS
Play @Rock
MongoD
B{ _id: “ABC”, name: “Acorda, Peão!” },
{ _id: “ABC”, name: “Acorda, Vagabundo!” },
{ _id: “ABC”, name: “Bebendo no Boteco” },
{ _id: “ABC”, name: “Correndo no Ibira” },
{ _id: “ABC”, name: “Dia de Chuva” },
{ _id: “ABC”, name: “Men’s Health” },
{ _id: “ABC”, name: “Trabalhando numa Boa” },
{ _id: “ABC”, name: “Whiskynho com a Rapaziada” },
db.playlists.find({
$or: [
{ "location": { $not: { $exists: true } } },
{ "location.name": "Brasil (BR)" },
{ "location.name": "São Paulo (SP)" },
{ "location.name": "São Paulo" },
],
}
Globalcode – Open4education
Optimização
APIiOS
Play @Rock
MongoD
B
db.plays.insert({
playlist: { name: "Rock" },
geolocation: {
coordinates: [-46.6749596, -23.598877],
locations: [
{ sourceid: “ABC”, level: “Country”, name: “Brasil
(BR)” },
{ sourceid: “DEF”, level: “State”, name: “São
Paulo (SP)” },
{ sourceid: “GHI”, level: “City”, name: “São Paulo”
},
],
}
});
Globalcode – Open4education
Closure
O MongoDB fornece toda a infraestrutura necessária para se
trabalhar com dados geolocalizados de maneira simples
Não é a toa que é usado/foi feito junto com o Foursquare
A nossa estrutura está pronta para crescer. Para colocar
novas cidades, basta mapea-las e importar o arquivo kml. A
demanda de playlists e spots vem crescendo nos últimos
meses sem que tivessemos que alterar a infraestrutura
para isso.
Globalcode – Open4education
Perguntas?
Globalcode – Open4education
jointheband@superplayer.fm
Globalcode – Open4education
Documentação MongoDB
http://docs.mongodb.org/manual/applications/geospatial-indexes/
http://docs.mongodb.org/manual/reference/operator/query-geospatial/

Contenu connexe

En vedette

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

En vedette (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

NoSQL Trilha - MongoDB para GeoJSON e Localização

  • 1. Globalcode – Open4educationGlobalcode – Open4education Trilha – NoSQL Caliel Costa Nerd, ouvinte de blues, pesquisador, esportista e fotógrafo amador, desenvolvedor e projetista de soluções em TI. Software Designer no Superplayer.
  • 2. Globalcode – Open4education Agenda • Telecurso de Geografia • Necessidade • GeoJSON • Consultas • Dados
  • 4. Globalcode – Open4education Planeta Terra Degrees, Minutes, Seconds to/from Decimal Degrees Cidade Latitude Longitude Porto Alegre -30.03128 -30° 1' 52.6074" Sul -51.2125487 51° 12' 45.1764" Oeste São Paulo -23.598877 -23° 35' 55.9572" Sul -46.6749596 -46° 40' 29.8554" Oeste Londres 51.4994438 51° 29' 57.9978" Norte 0 0° 0' 0" Hong Kong 22.3576782 22° 21' 27.6402" Norte 114.2196956 114° 13' 10.905" Leste
  • 5. Globalcode – Open4education Planeta Terra em Polígonos (21 pontos)
  • 6. Globalcode – Open4education Planeta Terra em Polígonos (84 Pontos)
  • 7. Globalcode – Open4education Planeta Terra em Polígonos (338 Pontos)
  • 8. Globalcode – Open4education Superplayer é um serviço de recomendação musical focado em melhorar todos os momentos da vida das pessoas através da trilha sonora perfeita. Startup brasileira Criado em 2012
  • 9. Globalcode – Open4education Web, Android, iOS, Windows Phone, ...
  • 13. Globalcode – Open4education MongoDB Na versão 2.4 (em 2013) foi introduzido o suporte a geometrias GeoJSON, podendo ser usadas em data e consultas.
  • 14. Globalcode – Open4education GeoJSON type coordinates Point deve ser uma posição simples MultiPoint deve ser um array de posição LineString deve ser um array de 2 ou mais posições MultiLineString deve ser um array de array de LineString Polygon deve ser um LinearRing, ou seja um LineString com 4 ou mais pontos, onde o primeiro e o último são posições equivalentes MultiPolygon deve ser um array de array de Polygon
  • 15. Globalcode – Open4education GeoJSON - Point { "type": "Point", "coordinates": [100.0, 0.0], }
  • 16. Globalcode – Open4education GeoJSON - LineString { "type": "LineString", "coordinates": [ [100.0, 0.0], [101.0, 1.0] ], }
  • 17. Globalcode – Open4education GeoJSON - Polygon { "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] ], }
  • 18. Globalcode – Open4education GeoJSON - MultiPoint { "type": "MultiPoint", "coordinates": [ [100.0, 0.0], [101.0, 1.0] ], }
  • 19. Globalcode – Open4education GeoJSON - MutiLineString { "type": "MultiLineString", "coordinates": [ [ [100.0, 0.0], [101.0, 1.0] ], [ [102.0, 2.0], [103.0, 3.0] ] ] }
  • 20. Globalcode – Open4education GeoJSON - MultiPolygon { "type": "MultiPolygon", "coordinates": [ [ [ [102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0] ] ], [ [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ], [ [100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ] ] ] }
  • 21. Globalcode – Open4education Brazil, seus 27 estados e respectivas capitais
  • 22. Globalcode – Open4education GeoJSON - Brasil { "_id" : ObjectId("54f4bd437da3100f4454e812"), "level" : "Country", "name" : "Brasil (BR)", "loc" : { "type" : "Polygon", "coordinates" : [ [ [ -44.69501, -1.817778 ], … 336 ... [-44.69501, -1.817778 ] ] ] } }
  • 23. Globalcode – Open4education GeoJSON - Estado São Paulo { "_id" : ObjectId("54f4bd5b7da3100f4454e82c"), "parentid" : "54f4bd437da3100f4454e812", "level" : "State", "name" : "São Paulo (SP)", "loc" : { "type" : "Polygon", "coordinates" : [ [ [ -49.3352376, -24.2290424 ], ...497... [ -49.3352376, -24.2290424 ] ] ] } }
  • 24. Globalcode – Open4education GeoJSON - Cidade São Paulo { "_id" : ObjectId("54f4bd5d7da3100f4454e846"), "parentid" : "54f4bd5b7da3100f4454e82c", "level" : "City", "name" : "São Paulo", "loc" : { "type" : "Polygon", "coordinates" : [ [ [ -46.53766020909132, -23.36963320731797 ], ..310.. [ -46.53766020909132, -23.36963320731797 ] ] ] } }
  • 25. Globalcode – Open4education Longitude e Latitude Vs Latitude e Longitude { "loc" : { "type" : "Polygon", "coordinates" : [ [ [ -46.53766020909132, -23.36963320731797 ], ..310.. [ -46.53766020909132, -23.36963320731797 ] ] ] } } Cidade Latitude Longitude São Paulo -23.598877 -23° 35' 55.9572" Sul -46.6749596 -46° 40' 29.8554" Oeste
  • 26. Globalcode – Open4education Longitude e Latitude Vs Latitude e Longitude “All documents must store location data in the same order. If you use latitude and longitude as your coordinate system, always store longitude first. MongoDB’s 2d spherical index operators only recognize [longitude, latitude] ordering.”
  • 27. Globalcode – Open4education Indexando GeoJSON Tipo Uso 2dsphere Suporta consultas que calculem geometrias em uma esfera tipo a Terra. 2d Gera um geohash de acordo com o valor das coordenadas haystack Este índice é um tipo especial de índice otimizado para retornar resultados sobre areas pequenas
  • 28. Globalcode – Open4education Indexando GeoJSON db.locations.createIndex({ "loc" : "2dsphere" }, { "name" : "loc_" }) • Índice esparso • Não pode ser usado como chave de sharding
  • 29. Globalcode – Open4education Consultas GeoJSON Function Objetivo $geoWithin Seleciona geometrias dentro dos limites de outra $geoIntersects Seleciona geometrias em interção com outra $near Retorna objetos na proximidade de um ponto $nearSphere Retorna objetos na proximidade de um ponto na esfera
  • 30. Globalcode – Open4education Onde estou? query: { "loc": { $geoIntersects: { $geometry: { type: "Point" , coordinates: [-51.2125487, -30.03128] } } } }
  • 31. Globalcode – Open4education Onde estou? query: { "loc": { $geoIntersects: { $geometry: { type: "Point" , coordinates: [-51.2125487, -30.03128] } } } } Result: Brasil (BR) Rio Grande do Sul (RS) Porto Alegre
  • 32. Globalcode – Open4education Onde estou?? query: { "loc": { $geoIntersects: { $geometry: { type: "Point" , coordinates: [-46.6749596, -23.598877] } } } }
  • 33. Globalcode – Open4education Onde estou?? query: { "loc": { $geoIntersects: { $geometry: { type: "Point" , coordinates: [-46.6749596, -23.598877] } } } } Result: Brasil (BR) São Paulo (SP) São Paulo
  • 34. Globalcode – Open4education Cidades perto de Gramado/RS { "level": "City", "loc": { $near: { $geometry: { type: "Point", coordinates: [-50.8586806,-29.3851463] } $minDistance: 1, $maxDistance: 300000, }, } }
  • 35. Globalcode – Open4education Cidades perto de Gramado/RS { "level": "City", "loc": { $near: { $geometry: { type: "Point", coordinates: [-50.8586806,-29.3851463] } $minDistance: 1, $maxDistance: 300000, }, } } Result: Porto Alegre Florianópolis
  • 36. Globalcode – Open4education Cidades perto de Campinas/SP query: { "level": "City", "loc": { $near: { $geometry: { type: "Point", coordinates: [-47.0562422, -22.9084404] } $minDistance: 60000, $maxDistance: 80000, } , } }
  • 37. Globalcode – Open4education Cidades perto de Campinas/SP query: { "level": "City", "loc": { $near: { $geometry: { type: "Point", coordinates: [-47.0562422, -22.9084404] } $minDistance: 60000, $maxDistance: 80000, } , } } Result: Osasco, Carapicuíba, Cotia, Vargem Grande Paulista
  • 38. Globalcode – Open4education $NearSphere Funciona igual ao Near só que ao invés de se usar distâncias em metros usa-se em radianos.
  • 43. Globalcode – Open4education Segmentação de Playlists Playlist Loc Type Loc Name Correndo no Ibira Polygon [ [ [long, lat] … ] ] São Paulo Rio 40 Graus Polygon [ [ [long, lat] … ] ] Rio de Janeiro Men’s Health Polygon [ [ [long, lat] … ] ] Brasil (BR)
  • 44. Globalcode – Open4education Buscando playlists query: { $or: [ { "location": { $not: { $exists: true } } }, { "location": { $geoIntersects: { $geometry: { type: "Point" , coordinates: [-46.6749596, -23.598877] } } } } ], } Result: Acorda, Peão!, Acorda, Vagabundo!, Bebendo no Boteco, Correndo no Ibira, Dia de Chuva, Men’s Health, Trabalhando numa Boa, Whiskynho com a Rapaziada, ...
  • 45. Globalcode – Open4education Buscando playlists query: { $or: [ { "location": { $not: { $exists: true } } }, { "location": { $geoIntersects: { $geometry: { type: "Point" , coordinates: [-47.0562422, -22.9084404] } } } } ], } Result: Acorda, Peão!, Acorda, Vagabundo!, Bebendo no Boteco, Dia de Chuva, Men’s Health, Trabalhando numa Boa, Whiskynho com a Rapaziada, ...
  • 46. Globalcode – Open4education Conteúdo Localizado • Playlists • Spots • Patrocínios de Playlists • Log de Playlists ouvidas • Log de Músicas (Tracks) ouvidas
  • 48. Globalcode – Open4education Optimização APIiOS Play @Rock MongoD B db.locations.find({ "loc": { $geoIntersects: { $geometry: { type: "Point" , coordinates: [-46.6749596, -23.598877] } } } } { _id: “ABC”, level: “Country”, name: “Brasil (BR)” }, { _id: “DEF”, level: “State”, name: “São Paulo (SP)” }, { _id: “GHI”, level: “City”, name: “São Paulo” },
  • 49. Globalcode – Open4education Optimização APIiOS Play @Rock MongoD B{ _id: “ABC”, name: “Acorda, Peão!” }, { _id: “ABC”, name: “Acorda, Vagabundo!” }, { _id: “ABC”, name: “Bebendo no Boteco” }, { _id: “ABC”, name: “Correndo no Ibira” }, { _id: “ABC”, name: “Dia de Chuva” }, { _id: “ABC”, name: “Men’s Health” }, { _id: “ABC”, name: “Trabalhando numa Boa” }, { _id: “ABC”, name: “Whiskynho com a Rapaziada” }, db.playlists.find({ $or: [ { "location": { $not: { $exists: true } } }, { "location.name": "Brasil (BR)" }, { "location.name": "São Paulo (SP)" }, { "location.name": "São Paulo" }, ], }
  • 50. Globalcode – Open4education Optimização APIiOS Play @Rock MongoD B db.plays.insert({ playlist: { name: "Rock" }, geolocation: { coordinates: [-46.6749596, -23.598877], locations: [ { sourceid: “ABC”, level: “Country”, name: “Brasil (BR)” }, { sourceid: “DEF”, level: “State”, name: “São Paulo (SP)” }, { sourceid: “GHI”, level: “City”, name: “São Paulo” }, ], } });
  • 51. Globalcode – Open4education Closure O MongoDB fornece toda a infraestrutura necessária para se trabalhar com dados geolocalizados de maneira simples Não é a toa que é usado/foi feito junto com o Foursquare A nossa estrutura está pronta para crescer. Para colocar novas cidades, basta mapea-las e importar o arquivo kml. A demanda de playlists e spots vem crescendo nos últimos meses sem que tivessemos que alterar a infraestrutura para isso.
  • 54. Globalcode – Open4education Documentação MongoDB http://docs.mongodb.org/manual/applications/geospatial-indexes/ http://docs.mongodb.org/manual/reference/operator/query-geospatial/