elasticsearch對數組進行搜索


寫在前面

我們在進行全文建搜的時候往往會添加很多前置條件,比如地區,時間,以及知識點樹,我們需要在搜索之前先進行過濾在進行搜索.

Array索引

es的數據類型中實際上是不包含數組類型的,在默認的情況下任何字段都可以包含0或者是更多的值,並且全部的值在這個數組中必須保持一致

In Elasticsearch, there is no dedicated array type. Any field can contain zero or more values by default, however, all values in the array must be of the same datatype. For instance:

  • an array of strings: [ “one”, “two” ]
  • an array of integers: [ 1, 2 ]
  • [ 1, 2, 3 ]
  • an array of objects: [ { “name”: “Mary”, “age”: 12 }, { “name”: “John”, “age”: 10 }]

NOTE
如果你想在數組中使用Object的類型,這種情況下是不被允許的,我們如果想使用Object就必須通過設置nested字段來生命這是一個對象數組!!

我們的映射字段不需要進行任何的配置,在默認的情況下我們就可以使用數組,這是開箱即用的:

{
  "mappings": {
    "test": {
      "properties": {
        "id": {
          "type": "long"
        },
        "points": {
          "type": "long"
        },
        "stem": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 2048
            }
          },
          "analyzer": "ik_smart"
        },
        "choose": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 2048
            }
          }
        }
      }
    }
  }
}

添加一條測試數據

{
  "id":1,
  "stem":"今天天氣真好啊",
  "choose":["誒呀我去","連上了"],
  "points":[23,31,53]
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

這里我直接指定了幾個基本的屬性,對同一個字段保存多個值進行測試

Array搜索

數組字段的搜索很簡單,我們平時遇到的場景也有很多,就像前文中提到的,當我們需要根據多個先決條件進行搜索的時候.
這里points保存了知識點的數組(有多個值構成),在搜素的時候我們為了保證該試題下包含所有的內容,就是用bool的must進行多個字段的搜索,實例如下:

{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "points": {
              "value": "23"
            }
          }
        },{
          "term": {
            "points": {
              "value": "31"
            }
          }
        },
        {
          "term": {
            "points": {
              "value": "53"
            }
          }
        }
      ]
    }
  }
}

搜索的結果可想而知,所有所有的內容都必須包含上述的三級知識點,如果需要不同級別的知識點,只需要對搜索條件進行調整即可.

  {
    "_index": "test_drup",
    "_type": "test",
    "_id": "1",
    "_score": 3,
    "_source": {
      "id": 1,
      "stem": "今天天氣真好啊",
      "choose": [
        "誒呀我去",
        "連上了"
      ],
      "points": [
        23,
        31,
        53
      ]
    }
  }
  • 1
  • 索結果只展示一部分

 

轉載: https://blog.csdn.net/qq_19663899/article/details/84945915

參考: https://www.cnblogs.com/ljhdo/p/4904430.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM