1. 程式人生 > 實用技巧 >ES基礎(四十一)物件及Nested物件

ES基礎(四十一)物件及Nested物件

課程demos

DELETE blog
# 設定blog的 Mapping
PUT /blog
{
  "mappings": {
    "properties": {
      "content": {
        "type": "text"
      },
      "time": {
        "type": "date"
      },
      "user": {
        "properties": {
          "city": {
            "type": "text"
          },
          
"userid": { "type": "long" }, "username": { "type": "keyword" } } } } } } # 插入一條 Blog 資訊 PUT blog/_doc/1 { "content":"I like Elasticsearch", "time":"2019-01-01T00:00:00", "user":{ "userid":1, "username":"Jack", "city":"Shanghai" } } # 查詢 Blog 資訊 POST blog
/_search { "query": { "bool": { "must": [ {"match": {"content": "Elasticsearch"}}, {"match": {"user.username": "Jack"}} ] } } } DELETE my_movies # 電影的Mapping資訊 PUT my_movies { "mappings" : { "properties" : { "actors" : { "properties" : {
"first_name" : { "type" : "keyword" }, "last_name" : { "type" : "keyword" } } }, "title" : { "type" : "text", "fields" : { "keyword" : { "type" : "keyword", "ignore_above" : 256 } } } } } } # 寫入一條電影資訊 POST my_movies/_doc/1 { "title":"Speed", "actors":[ { "first_name":"Keanu", "last_name":"Reeves" }, { "first_name":"Dennis", "last_name":"Hopper" } ] } # 查詢電影資訊 POST my_movies/_search { "query": { "bool": { "must": [ {"match": {"actors.first_name": "Keanu"}}, {"match": {"actors.last_name": "Hopper"}} ] } } } DELETE my_movies # 建立 Nested 物件 Mapping PUT my_movies { "mappings" : { "properties" : { "actors" : { "type": "nested", "properties" : { "first_name" : {"type" : "keyword"}, "last_name" : {"type" : "keyword"} }}, "title" : { "type" : "text", "fields" : {"keyword":{"type":"keyword","ignore_above":256}} } } } } POST my_movies/_doc/1 { "title":"Speed", "actors":[ { "first_name":"Keanu", "last_name":"Reeves" }, { "first_name":"Dennis", "last_name":"Hopper" } ] } # Nested 查詢 POST my_movies/_search { "query": { "bool": { "must": [ {"match": {"title": "Speed"}}, { "nested": { "path": "actors", "query": { "bool": { "must": [ {"match": { "actors.first_name": "Keanu" }}, {"match": { "actors.last_name": "Hopper" }} ] } } } } ] } } } # Nested Aggregation POST my_movies/_search { "size": 0, "aggs": { "actors": { "nested": { "path": "actors" }, "aggs": { "actor_name": { "terms": { "field": "actors.first_name", "size": 10 } } } } } } # 普通 aggregation不工作 POST my_movies/_search { "size": 0, "aggs": { "NAME": { "terms": { "field": "actors.first_name", "size": 10 } } } }