我正在尝试在 Elasticsearch 上索引具有属性值对的文档。示例文档:
{
id: 1,
name: "metamorphosis",
author: "franz kafka"
}
{
id: 2,
name: "techcorp laptop model x",
type: "computer",
memorygb: 4
}
{
id: 3,
name: "ss2014 formal shoe x",
color: "black",
size: 42,
price: 124.99
}
然后,我需要这样的查询:
1. "author" EQUALS "franz kafka"
2. "type" EQUALS "computer" AND "memorygb" GREATER THAN 4
3. "color" EQUALS "black" OR ("size" EQUALS 42 AND price LESS THAN 200.00)
存储这些文档以高效查询它们的最佳方式是什么?我应该完全按照示例中的方式存储它们吗?或者我应该像这样存储它们:
{
fields: [
{ "type": "computer" },
{ "memorygb": 4 }
]
}
或喜欢:
{
fields: [
{ "key": "type", "value": "computer" },
{ "key": "memorygb", "value": 4 }
]
}
我应该如何映射我的索引以便能够执行相等和范围查询?
最佳答案
如果有人仍在寻找答案,我写了一篇关于如何将任意数据索引到 Elasticsearch 中然后按特定字段和值进行搜索的帖子。所有这一切,都不会破坏您的索引映射。
帖子:http://smnh.me/indexing-and-searching-arbitrary-json-data-using-elasticsearch/
简而言之,您需要创建帖子中描述的特殊索引。然后,您需要使用 flattenData
函数 https://gist.github.com/smnh/30f96028511e1440b7b02ea559858af4 来展平数据.然后,扁平化的数据可以安全地索引到 Elasticsearch 索引中。
例如:
flattenData({
id: 1,
name: "metamorphosis",
author: "franz kafka"
});
将产生:
[
{
"key": "id",
"type": "long",
"key_type": "id.long",
"value_long": 1
},
{
"key": "name",
"type": "string",
"key_type": "name.string",
"value_string": "metamorphosis"
},
{
"key": "author",
"type": "string",
"key_type": "author.string",
"value_string": "franz kafka"
}
]
和
flattenData({
id: 2,
name: "techcorp laptop model x",
type: "computer",
memorygb: 4
});
将产生:
[
{
"key": "id",
"type": "long",
"key_type": "id.long",
"value_long": 2
},
{
"key": "name",
"type": "string",
"key_type": "name.string",
"value_string": "techcorp laptop model x"
},
{
"key": "type",
"type": "string",
"key_type": "type.string",
"value_string": "computer"
},
{
"key": "memorygb",
"type": "long",
"key_type": "memorygb.long",
"value_long": 4
}
]
然后您可以使用构建 Elasticsearch 查询来查询您的数据。每个查询都应指定键和值的类型。如果您不确定索引有哪些键或类型,您可以运行聚合来找出答案,这也在帖子中讨论。
例如,要查找 author == "franz kafka"
所在的文档,您需要执行以下查询:
{
"query": {
"nested": {
"path": "flatData",
"query": {
"bool": {
"must": [
{"term": {"flatData.key": "author"}},
{"match": {"flatData.value_string": "franz kafka"}}
]
}
}
}
}
}
要查找 type == "computer"and memorygb > 4
的文档,您需要执行以下查询:
{
"query": {
"bool": {
"must": [
{
"nested": {
"path": "flatData",
"query": {
"bool": {
"must": [
{"term": {"flatData.key": "type"}},
{"match": {"flatData.value_string": "computer"}}
]
}
}
}
},
{
"nested": {
"path": "flatData",
"query": {
"bool": {
"must": [
{"term": {"flatData.key": "memorygb"}},
{"range": {"flatData.value_long": {"gt": 4}}}
]
}
}
}
}
]
}
}
}
在这里,因为我们希望相同的文档同时匹配这两个条件,所以我们使用外部 bool
查询和 must
子句包装两个 嵌套
查询。
关于elasticsearch - 在 Elasticsearch 上索引任意属性值对的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28583987/