# ElasticSearch
# Operations
# Create
from elasticsearch import Elasticsearch
es = Elasticsearch('http://localhost:9200')
mapping = {
"mappings": {
"properties": {
"context": {"type": "text", "fields": {"keyword": {"type": "keyword", "ignore_above": 256}}},
"item_code":{"type": "text", "fields": {"keyword": {"type": "keyword", "ignore_above": 256}}}
}
},
"settings": {
"index.search.slowlog.threshold.query.warn": "1s",
"index.search.slowlog.threshold.fetch.warn": "1s",
"analysis": {
"analyzer": {
"demo_analyzer":{"tokenizer": "demo_tokenizer", "filter": ["custom_stop"]}
},
"filter": {
"custom_stop":{"type": "stop", "stopwords":[".", ""]},
"custom_gram": {"type": "common_grams", "common_words": ["x"]}
},
"tokenizer": {
"demo_tokenizer": {
"type": "pattern", "pattern": "([^\\p{L}\\d.]+))", "lowercase": true, "flags": "UNICODE_CHARACTER_CLASS"
}
}
}
}
}
es.indices.create(index='custom_index', body=mapping)
records = {
'key': [{'item_code': '123', 'context': '2333'}]
}
idx = 1
for _, document_list in records.items():
for one_document in document_list:
es.index(index='custom_index', id=idx, body=one_document)
idx += 1
# Count
es.count(index='custom_index')
# Delete
es.indices.delete(index='po_table')
# Query
"""GET index/_search"""
# simple search
{
"query": {
"match": {
"$FIELD": "some value"
}
}
}
# term search
{
"query": {
"terms": {
"$FIELD": [
"some value"
]
}
}
}
# multi search
{
"query": {
"multi_match": {
"type": "most_fields",
"query": "some text",
"fields": ["$FIELD1", "$FIELD2^2"]
}
}
}
# span search
{
"query":{
"span_near" : {
"clauses" : [
{ "span_term" : {"$FIELD1" : "25" }},
{ "span_term" : {"$FIELD1" : "25" }},
{ "span_term" : {"$FIELD1" : "3" }}
],
"slop" : 3,
"boost": 30,
"in_order" : true
}
}
}
# filter after search
{
"size": 1,
"query": {
"bool": {
"must": [
{
"match": {
"$FIELD": "some value"
}
}
],
"filter": [
{
"terms": {
"$FIELD": ["some value1", "some value2"]
}
}
]
}
}
}
# Analyze
# POST index/_analyze
{
"analyzer": "standard",
"text": "some text"
}
# Setting
# POST po_test/_close
# PUT po_test/_settings
# POST po_test/_open