小编典典

在ElasticSearch中加入查询

elasticsearch

有什么办法(查询)在ElasticSearch中加入以下2个JSON

{
product_id: "1111",
price: "23.56",
stock: "100"
}

{
product_id: "1111",
category: "iPhone case",
manufacturer: "Belkin"
}

以上2种JSON在Logstash中以2种不同类型处理(输入),因此它们的索引在Elasticsearch中归档的不同“类型”中可用。

我想要的是在product_id字段上加入2个JSON。


阅读 304

收藏
2020-06-22

共1个答案

小编典典

当您说加入时,这取决于您的打算。Elasticsearch与支持表之间的JOIN的常规数据库不同。它是一个文本搜索引擎,用于管理索引中的文档。

另一方面,您可以使用每种类型共有的字段在多个类型的同一索引内进行搜索。

例如,以您的数据为例,我可以创建一个具有2种类型的索引,它们的数据如下所示:

curl -XPOST localhost:9200/product -d '{
    "settings" : {
        "number_of_shards" : 5
    }
}'

curl -XPOST localhost:9200/product/type1/_mapping -d '{
        "type1" : {
            "properties" : {
                "product_id" : { "type" : "string" },
                "price" : { "type" : "integer" },
                "stock" : { "type" : "integer" }
            }
        }   
}'

curl -XPOST localhost:9200/product/type2/_mapping -d '{
        "type2" : {
            "properties" : {
                "product_id" : { "type" : "string" },
                "category" : { "type" : "string" },
                "manufacturer" : { "type" : "string" }
            }
        }
}'

curl -XPOST localhost:9200/product/type1/1 -d '{
        product_id: "1111", 
        price: "23",
        stock: "100"
}'

curl -XPOST localhost:9200/product/type2/1 -d '{
        product_id: "1111",
        category: "iPhone case",
        manufacturer: "Belkin"
}'

我有效地创建了一个名为product的索引,具有2个type1和type2。现在,我可以执行以下查询,它将返回两个文档:

curl -XGET 'http://localhost:9200/product/_search?pretty=1' -d '{
    "query": {
        "query_string" : {
            "query" : "product_id:1111"
        }
    }
}'

{
  "took" : 95,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 2,
    "max_score" : 0.5945348,
    "hits" : [ {
      "_index" : "product",
      "_type" : "type1",
      "_id" : "1",
      "_score" : 0.5945348, "_source" : {
    product_id: "1111",
    price: "23",
    stock: "100"
}
    }, {
      "_index" : "product",
      "_type" : "type2",
      "_id" : "1",
      "_score" : 0.5945348, "_source" : {
    product_id: "1111",
    category: "iPhone case",
    manufacturer: "Belkin"
}
    } ]
  }
}

原因是因为Elasticsearch将搜索该索引内的所有文档,而不管其类型如何。这与JOIN还是有区别的,在这种意义上,Elasticsearch不会对属于每种类型的文档进行笛卡尔积。

希望能有所帮助

2020-06-22