Yanick Rochon
Yanick Rochon

Reputation: 53531

ElasticSearch client.indices.putMapping always fail

I really don't understand the docs. Even after reading a few SO questions and answers (ex: this one). I have this code

let indexMapping = {
  'foo': {
    name: { type: 'string', index: 'analyzed' },
    value: { index: 'no' },
    dynamic_templates: [ {
      customRule: {
        path_match: 'bar.*',
        mapping: { type: '{dynamic_type}', index: 'no' }
      }
    } ]
  }
};
let indexName = 'foos';
let typeName = 'foo';

client.indices.putMapping({
  index: indexName,
  type: typeName,
  [typeName]: {
    properties: indexMapping[typeName]
  }
}).catch(function (err) {
  console.error(err.stack || err);
});

And I always get

Error: [action_request_validation_exception] Validation Failed: 1: mapping source is empty;

What am I doing wrong?

More info

My index is newly created, and there are no documents added or any types currently defined. This is a new, blank, index that I want to set mappings to before adding and indexing documents.

Upvotes: 1

Views: 4885

Answers (2)

Val
Val

Reputation: 217274

Dynamic templates declarations should go at the same level as the properties of a mapping type, so your code should look like this instead:

let indexName = 'foos';
let typeName = 'foo';

let indexMapping = {
  'properties': {
    [typeName]: {
      name: { type: 'string', index: 'analyzed' },
      value: { type: 'string', index: 'no' }
    }
  },
  'dynamic_templates': [ {
      customRule: {
          path_match: 'bar.*',
          mapping: { type: '{dynamic_type}', index: 'no' }
      }
  } ]
};

client.indices.putMapping({
  index: indexName,
  type: typeName,
  body: indexMapping
}).catch(function (err) {
  console.error(err.stack || err);
});

Upvotes: 1

Or Weinberger
Or Weinberger

Reputation: 7472

The syntax you're using is a bit off, your final call should look like this:

client.indices.putMapping({
  index: 'foos',
  type: 'foo',
  body: {
    "foo": {
      properties: {
        name: {
          type: 'string',
          index: 'analyzed'
        },
        value: {
          index: 'no'
        },
        dynamic_templates: [{
          customRule: {
            path_match: 'bar.*',
            mapping: {
              type: '{dynamic_type}',
              index: 'no'
            }
          }
        }]
      }
    }
  }
}).catch(function(err) {
  console.error(err.stack || err);
});

Also note that you must define a type for value as you did for name and your dynamic template section is also missing the fields object.

Upvotes: 0

Related Questions