简体   繁体   中英

Searchkick: how to save records in ElasticSearch in different indices based on record timestamp?

I have a Rails Model with Searchkick.

I want my model instances to be saved in ElasticSearch in different indices based on the month creation of the instance. Lets say I have the following instances in my Model:

  • A created the 03/25/2021
  • B created the 03/28/2021
  • C created the 04/01/2021

Instead of having one ES index (which is the default behavior for Searchkick), how can I store when my instances are created:

  • A & B in ES index labeled: model_2021_03
  • C in ES index labeled: model_2021_04

From what I understand, there are two main steps:

  1. Create Multiple Index(indices)
  2. Store the document in one of those index.

Idea here is making the index as "Write_Index" in which you want to put the document and mark others as "Read_Index".

So you can start with:

1. Creating an Index Template.

    PUT /_index_template/model_template

    {
       "index_patterns": [
            "model*"
        ],
        "priority": 1,
        "template": {
            "aliases": {
                "model":{}
            },
        "mappings": {
          "dynamic":"strict",
          "_source":
          {"enabled": false},
          "properties": {
           //your filed mappings here
          }
        },
        "settings": {
        "index": {
          "number_of_shards": 1,  
          "number_of_replicas": 3
        }
      }
      }
    }

 2.Create an index for a particular month,which will follow the model template(in step 1) with an naming strategy in your code 

  PUT model_YYYY_MM

Ex: lets say, you create two index model_2021_03, model_2021_04, now you want to store the documents in one of them,

Idea here is to mark the index, that you want to store the document in as "Write_Index" and all other as "Read_Index", so when you store the document using alias name("model") here, it will get stored in write index by default.

3. Making the index as write index and others as read
POST /_aliases
{
  "actions": [
    {"add": 
    {"index": "model_2021_04",
    "alias": "model",
    "is_write_index": true}
    },
     {"add": 
    {"index": "model_2021_03",
    "alias": "model",
    "is_write_index": false}
    }
  ]
}

4.Finally putting documents in index using alias name

PUT /model/_doc/1
{
//your data here
}
     

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM