martes, 23 de junio de 2020

Postgres - Match + distance(PostGIS)

Samples:

https://www.freecodecamp.org/news/fuzzy-string-matching-with-postgresql/

extensiones requeridas:

CREATE EXTENSION fuzzystrmatch;
CREATE EXTENSION pg_trgm;
CREATE EXTENSION postgis;
sample:
select distinct a.id, a.name, 
  ST_Distance_Spheroid(a.geom, b.geom, 'SPHEROID["WGS 84",6378137,298.257223563]' ) as d,
  b.name2
 from table1 a, table2 b 
 where trim(a.name) = trim(b.name2)   
  and ST_Distance_Spheroid(a.geom, b.geom, 'SPHEROID["WGS 84",6378137,298.257223563]' ) < 7000
  and
     ( 
     SIMILARITY(a.name, b.name2 ) > 0.4 
   or (a.name % b.name2  )
   or (SOUNDEX(a.name) = SOUNDEX(b.name2) )
   --or (LEVENSHTEIN(a.name, b.name2) < 4 )
     )
 order by a."IdLoc", ST_Distance_Spheroid(a.geom, b.geom, 'SPHEROID["WGS 84",6378137,298.257223563]' 
Encuentra parecidos en el rango de 7Km.//

viernes, 19 de enero de 2018

row_number (genera números correlativos)

http://www.postgresqltutorial.com/postgresql-row_number/

:)  more clear water

SELECT product_id, product_name, group_id, ROW_NUMBER () OVER ( PARTITION BY group_id ORDER BY product_name ) FROM products;

lunes, 26 de junio de 2017

jueves, 25 de mayo de 2017

Postgres dblink - Consultando tablas de otra base de datos

With PostgreSQL 9.1 or later, installation of additional modules has been simplified. Registered extensions (including dblink) can be installed with CREATE EXTENSION:

CREATE EXTENSION dblink;

Run once per database. Or run it in the standard system database template1 to add it to every newly created DB automatically. Details in the manual.


Ejemplo:

select t.*
 from dblink('host=localhost dbname=bd user=postgres password=secret', 
                    'select id, name from table')
  as t(id int, name varchar)
 where id < 100
 order by id desc


Mas ejemplos:

http://www.postgresonline.com/journal/archives/44-Using-DbLink-to-access-other-PostgreSQL-Databases-and-Servers.html

martes, 23 de mayo de 2017

pgFormatter - Formateando query

http://sqlformat.darold.net/

This SQL formatter/beautifier supports keywords from SQL-92, SQL-99, SQL-2003, SQL-2008, SQL-2011 and PostgreSQL specifics keywords. May works with any other databases too.

Interesante... nice ;)

Links:

    Website: http://sqlformat.darold.net/
    Download: http://sourceforge.net/projects/pgformatter/
    Development: https://github.com/darold/pgFormatter
    Changelog: https://github.com/darold/pgFormatter/blob/master/ChangeLog

Emparejamiento difuso - Fuzzy Matching Algorithms To the Rescue

Levenshtein is a great algorithm to detect typos in a search query. It operates based on how distant one search term is from another term. Starting with the “source” word, it counts the number of operations (additions, subtractions, substitutions) it takes to arrive at the “destination” word. This make the Levenshtein algorithm particularly good at catching seach typos, and uncommon spellings.
(https://mrfrosti.com/2011/08/22/fuzzy-matching-in-postgresql-with-nicknames/)

Previamente habilitar la extensión:

CREATE EXTENSION fuzzystrmatch;

Ejemplo:

SELECT levenshtein('iden', 'idem');

Ejemplo: comparando el campo NOMBRE de dos tablas:

SELECT a.nombre1, b.nombre2, levenshtein(a.nombre1, b.nombre2) as leven
from tabla1 a, tabla2 b
where 
and levenshtein(a.nombre_com, b.nombre_c_1) >=  0
order by leven

links relacionados:

https://www.postgresql.org/docs/9.3/static/functions-matching.html
https://www.laurivan.com/fuzzy-string-matching-in-postgresql/
https://www.rdegges.com/2013/easy-fuzzy-text-searching-with-postgresql/

martes, 25 de abril de 2017

Vim - mínimo

Search & replace: 
:11,15s/old/new/gc         with c_onfirmation in a range
:%s/old/new                    all
:21,$
:.,$                                    current line
:.,+100

Ciertos caracteres especiales (/ & ! . ^ * $ \ ?) tienen un significado particular en el proceso de búsqueda, y por lo tanto deben especificarse de un modo especial cuando están incluidos en el string a buscar, precediéndolos por la barra hacia atrás (\).

Read  oother file:
:r  ~/home/ric/file.txt
:r! sed -n 7,15p ~/home/ric/file.txt              (block)

Indent/ Unindent:
gg=G                all
in mode insert   CTRL-T   indent
                          CTRL-D   unindent
in mode normal  >>    <<     line current

Indent bloques:
v    marcar bloque - visual mode
<    indenta izq,   > derecha


Borrar/copiar/pegar:
dgg      del cursor al principio
dG                        al final
3dd      3 líneas

3yy      copiar 3 líneas
p           debajo de la línea  P arriba

Modo columna:
CTRL-V

Bloques - copiar/pegar
mb    - en inicio de bloque marca con el nombre b (ejm)
y'b     - al final de bloque   (d para borrar)
luego con p  ó  P en la ubicación deseada

Bloques - copiar/pegar con número de línea
:7,10y           (marca para copiar de la línea 7 a la 10, con d para borrar)
luego con p ó P en la ubicación deseada

Desactivar autoindent temporalmente para copiar
:set paste
:set nopaste    (set noai?)

Install plugin EMMET:

## install emmet
cd Downloads
git clone https://github.com/mattn/emmet-vim.git
cd ~/.vim
cp -r ~/Downloads/emmet-vim/plugin/ .
cp -r ~/Downloads/emmet-vim/autoload/ .

## redefine trigger key <c-y>  ->  ,,
## add a .vimrc
let g:user_emmet_leader_key=','

Refs.:
https://medium.com/vim-drops/be-a-html-ninja-with-emmet-for-vim-feee15447ef1
https://raw.githubusercontent.com/mattn/emmet-vim/master/TUTORIAL

Insert new line without entering mode insert:
nmap <F8> o<Esc>
nmap <F9> O<Esc>

Registers:


"ry5w                 # register yank 5 palabras,  para copiar: "p"
:reg                    # lista los registros realizados, para copiar:  "Cp 
                            # donde C es el caracter asignado automáticamente por register