DEV Community

Kaziu
Kaziu

Posted on Edited on

Elasticsearch: The Very Basics

(Notes for myself)

Compared with MySQL

MySQL ES
database index
row (one record) document
column type mapping

So "rebuilding an index" is like recreating a database.

Data format

ES uses JSON

{
    "deal": {
      "id": 1,
      "name": "Proposal to TOYOTA",
      "has_materials": true
    }
  }
Enter fullscreen mode Exit fullscreen mode

Writing search queries

Basic form

GET index name/_search
{
  "query": {
    conditions go here
  }
}
Enter fullscreen mode Exit fullscreen mode

query is the SQL WHERE clause.

I want an exact match (term)

In SQL:
WHERE has_materials = true

{
  "query": {
    "term": { "deal.has_materials": true }
  }
}
Enter fullscreen mode Exit fullscreen mode

I want to combine conditions with AND (= bool + filter)

In SQL:
WHERE has_materials = true AND invoice_id = 3

{
  "query": {
    "bool": {
      "filter": [
        { "term": { "deal.has_materials": true } },
        { "term": { "deal.invoice.id": 3 } }
      ]
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Listing conditions in the bool + filter array means AND.

I want a partial text match (= match)

In SQL:
WHERE name LIKE '%Toyota%'

{
  "query": {
    "match": { "deal.name": "Toyota" }
  }
}
Enter fullscreen mode Exit fullscreen mode

What's a mapping?

Same as MySQL's "column type definitions (int, varchar…)".
You declare each field's type in advance.

{
  "deal": {
    "id":            { "type": "integer" },
    "name":          { "type": "text" },
    "has_materials": { "type": "boolean" }
  }
}
Enter fullscreen mode Exit fullscreen mode

What if I change the mapping?

You have to rebuild the index.

Top comments (0)