Querystring search on array elements in Elastic Search

后端 未结 3 1032
孤独总比滥情好
孤独总比滥情好 2020-12-12 22:40

I\'m trying to learn elasticsearch with a simple example application, that lists quotations associated with people. The example mapping might look like:

{ 
          


        
相关标签:
3条回答
  • 2020-12-12 22:54

    If scripting is enabled, this should work:

    "script": {
       "inline": "for(element in _source.quotations) { if(element == 'this' && element == 'these') {return true;} }; return false;"
     }
    
    0 讨论(0)
  • 2020-12-12 23:07

    For that requirement to be achieved, you need to look at nested objects, not to query a flattened list of values but individual values from that nested object. For example:

    {
      "mappings": {
        "people": {
          "properties": {
            "name": {
              "type": "string"
            },
            "quotations": {
              "type": "nested",
              "properties": {
                "value": {
                  "type": "string"
                }
              }
            }
          }
        }
      }
    }
    

    Values:

    {"name":"Mr A","quotations":[{"value": "quotation one, this and that and these"}, {"value": "quotation two, those and that"}]}
    {"name":"Mr B","quotations":[{"value": "quotation three, this and that"}, {"value": "quotation four, those and these"}]}
    

    Query:

    {
      "query": {
        "nested": {
          "path": "quotations",
          "query": {
            "bool": {
              "must": [
                { "match": {"quotations.value": "this"}},
                { "match": {"quotations.value": "these"}}
              ]
            }
          }
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-12 23:17

    Unfortunately there is no good way to do that. https://web.archive.org/web/20141021073225/http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/complex-core-fields.html

    When you get a document back from Elasticsearch, any arrays will be in the same order as when you indexed the document. The _source field that you get back contains exactly the same JSON document that you indexed.

    However, arrays are indexed — made searchable — as multi-value fields, which are unordered. At search time you can’t refer to “the first element” or “the last element”. Rather think of an array as a bag of values.

    In other words, it is always considering all values in the array.

    This will return only Mr A

    {
      "query": {
        "match": {
          "quotations": {
            "query": "quotation one",
            "operator": "AND"
          }
        }
      }
    }
    

    But this will return both Mr A & Mr B:

    {
      "query": {
        "match": {
          "quotations": {
            "query": "this these",
            "operator": "AND"
          }
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题