viernes, 22 de diciembre de 2023

Configurando Elasticsearch para que no distinga tildes o eñes

Típico problema, indexamos un documento con el texto "Menganita conduce un camión", buscamos "camion", sin la tilde, y no aparece el documento.

Basado en este artículo: https://sacavix.com/2020/10/elasticsearch-para-espanol-acentos-y-raiz-de-palabras/


Receta rápida

1. Reconfiguramos el índice que nos interese:

curl -XPUT http://localhost:9200/_template/miindicetemplate -H "Content-Type: application/json" -d '
{
  "index_patterns": "miindice",
  "settings": {
    "number_of_shards": 2,
    "number_of_replicas": 1,
    "analysis": {
      "analyzer":{
      "mianalizador": {
          "tokenizer": "standard",
          "filter":  [ "lowercase", "asciifolding", "default_spanish_stopwords", "default_spanish_stemmer" ]
      }
    },
    "filter" : {
        "default_spanish_stemmer" : {
            "type" : "stemmer",
            "name" : "spanish"
        },
        "default_spanish_stopwords": {
            "type":        "stop",
            "stopwords": [ "_spanish_" ]
        }
    }
   }
  },
  "mappings": {
      "properties": {
        "title": {
          "type": "text",
          "analyzer": "mianalizador",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "leadIn": {
          "type": "text",
          "analyzer": "mianalizador",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "author": {
          "type": "text",
          "analyzer": "mianalizador",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "pretitle": {
          "type": "text",
          "analyzer": "mianalizador",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        }
      }
    }
}'

2. Borramos el índice

curl -X DELETE http://localhost:9200/miindice



3. Indexamos de nuevo el contenido. Si es un proyecto Symfony con FOSElastica:

symfony console fos:elastica:reset
symfony console fos:elastica:populate