如何在elasticsearch中使用映射?

时间:2015-05-05 08:48:13

标签: elasticsearch logstash

使用logstash处理日志后,我的所有字段都具有相同的类型' STRING所以我想在elasticsearch中使用映射来更改某些类型,如ip,port等..但我不知道如何这样做,我是ElasticSearch中的超级初学者..

有任何帮助吗?

1 个答案:

答案 0 :(得分:2)

首先要做的是在Elasticsearch中安装Marvel插件。它允许您非常轻松地使用Elasticsearch REST API - 索引文档,修改映射等。

转到Elasticsearch文件夹并运行:

bin/plugin -i elasticsearch/marvel/latest

然后转到http://localhost:9200/_plugin/marvel/sense/index.html访问Marvel Sense,您可以从中发送命令。 Marvel本身为您提供有关Elasticsearch索引,性能统计等的仪表板:http://localhost:9200/_plugin/marvel/

在Sense中,您可以运行:

GET /_cat/indices

了解Elasticsearch实例中存在哪些索引。

假设有一个名为logstash的索引。

您可以通过运行以下方式检查其映射:

GET /logstash/_mapping

Elasticsearch将返回描述索引映射的JSON文档。它可能是这样的:

{
   "logstash": {
      "mappings": {
         "doc": {
            "properties": {
               "Foo": {
                  "properties": {
                     "x": {
                        "type": "String"
                     },
                     "y": {
                        "type": "String"
                     }
                  }
               }
            }
         }
      }
   }
}

...在这种情况下,doc是您索引文档的文档类型(集合)。在Sense中,您可以按如下方式索引文档:

PUT logstash/doc/1
{
  "Foo": {
    "x":"500",
    "y":"200"
  }
}

...这是一个在id 1下索引JSON对象的命令。

一旦Foo.x等文档字段具有String类型,就无法将其更改为数字。您必须先设置映射,然后重新编制索引。

首先删除索引:

DELETE logstash

然后创建索引并按如下方式设置映射:

PUT logstash
PUT logstash/doc/_mapping
{
   "doc": {
      "properties": {
         "Foo": {
            "properties": {
               "x": {
                  "type": "long"
               },
               "y": {
                  "type": "long"
               }
            }
         }
      }
   }
}

现在,即使您使用属性作为JSON字符串索引doc,Elastisearch也会将它们转换为数字:

PUT logstash/doc/1
{
  "Foo": {
    "x":"500",
    "y":"200"
  }
}

搜索新文档:

GET logstash/_search

请注意,_source字段中返回的文档与您将其发送到Elasticsearch的方式完全相同 - 这是故意的,Elasticsearch始终以这种方式保留原始文档。但是,属性被索引为数字。您可以运行范围查询以确认:

GET logstash/_search
{
  "query":{
    "range" : {
        "Foo.x" : {
            "gte" : 500
        }
    }
  }
}

对于Logstash,您可能希望为索引名logstash-*设置映射模板,因为Logstash会自动创建新索引:http://www.elastic.co/guide/en/elasticsearch/reference/1.5/indices-templates.html