我正在使用以下代码在 Elasticsearch 中创建索引和加载数据
from elasticsearch import helpers, Elasticsearch
import csv
es = Elasticsearch()
es = Elasticsearch('localhost:9200')
index_name='wordcloud_data'
with open('./csv-data/' + index_name +'.csv') as f:
reader = csv.DictReader(f)
helpers.bulk(es, reader, index=index_name, doc_type='my-type')
print ("done")
我的CSV数据如下
date,word_data,word_count
2017-06-17,luxury vehicle,11
2017-06-17,signifies acceptance,17
2017-06-17,agency imposed,16
2017-06-17,customer appreciation,11
数据加载正常,但数据类型不准确 我如何强制它说 word_count 是整数而不是文本 看看它是如何计算出日期类型的? 有没有办法自动找出 int 数据类型?或者通过传递一些参数?
此外,如果我愿意,我应该如何增加 ignore_above 或将其从某些字段中删除。基本没有字数限制?
{
"wordcloud_data" : {
"mappings" : {
"my-type" : {
"properties" : {
"date" : {
"type" : "date"
},
"word_count" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"word_data" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
}
}
}
}
最佳答案
您需要create a mapping这将描述字段类型。
通过 elasticsearch-py
客户端,这可以使用 es.indices.put_mapping
完成或 index.create
方法,通过将描述映射的 JSON 文档传递给它,like shown in this SO answer .它会是这样的:
es.indices.put_mapping(
index="wordcloud_data",
doc_type="my-type",
body={
"properties": {
"date": {"type":"date"},
"word_data": {"type": "text"},
"word_count": {"type": "integer"}
}
}
)
但是,我建议看一下 elasticsearch-dsl
提供 much nicer declarative API to describe things 的包.这将是沿着这些路线的东西(未经测试):
from elasticsearch_dsl import DocType, Date, Integer, Text
from elasticsearch_dsl.connections import connections
from elasticsearch.helpers import bulk
connections.create_connection(hosts=["localhost"])
class WordCloud(DocType):
word_data = Text()
word_count = Integer()
date = Date()
class Index:
name = "wordcloud_data"
doc_type = "my_type" # If you need it to be called so
WordCloud.init()
with open("./csv-data/%s.csv" % index_name) as f:
reader = csv.DictReader(f)
bulk(
connections.get_connection(),
(WordCloud(**row).to_dict(True) for row in reader)
)
请注意,我没有尝试我发布的代码 - 只是写了它。手头没有 ES 服务器来测试。可能会有一些小错误或错别字(如有请指出),但总体思路应该是正确的。
关于python elasticsearch批量索引数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44696039/