Search code examples
jsonluceneelasticsearchprefix

Multiple Fields for Prefix in ElasticSearch and auto From and Size limit


I got 2 questions related to ElasticSearch.

1) First Question, I have this query with prefix

"must": [
        {
           "prefix": {
              "user": "John"
           }
        }
     ]

with this query, I can Prefix John with User field so it results those documents in which John is found in User field. Now how can I make this query to see if John is prefixed in either any of User or email fields.


2) Second Question, I know we can apply Size and from in ElasticSearch to limit Result but I want to know that do I have to explicitly provide Size and from every time I query in ElasticSearch to continue last result or is there any other way to let the ElasticSearch do it for me that I just query and it will give results in a series left from previous.


Solution

  • First, note that the prefix-query does not do any text analysis, so you will not be matching e.g. john with your query.

    You should look into the multi_match-query which takes the options of the match-query as well. Thus, you can combine multi_match with phrase_prefix and get the best of both: matching on multiple fields, and text analysis.

    Here is a runnable example you can play with: https://www.found.no/play/gist/8197442

    #!/bin/bash
    
    export ELASTICSEARCH_ENDPOINT="http://localhost:9200"
    
    # Index documents
    curl -XPOST "$ELASTICSEARCH_ENDPOINT/_bulk?refresh=true" -d '
    {"index":{"_index":"play","_type":"type"}}
    {"user":"John Smith","email":"john.smith@gmail.com"}
    {"index":{"_index":"play","_type":"type"}}
    {"user":"Alice Smith","email":"john.smith@gmail.com"}
    '
    
    # Do searches
    
    curl -XPOST "$ELASTICSEARCH_ENDPOINT/_search?pretty" -d '
    {
        "query": {
            "multi_match": {
                "fields": [
                    "user",
                    "email"
                ],
                "query": "john",
                "operator": "and",
                "type": "phrase_prefix"
            }
        }
    }
    '
    

    For your second question, look into the scroll API.