def fn_query(query_vec, q="*", cosine=False):
    """
    Construct an Elasticsearch function score query.

    The query takes as parameters:
        - the field in the candidate document that contains the factor vector
        - the query vector
        - a flag indicating whether to use dot product or cosine similarity (normalized dot product) for scores

    The query vector passed in will be the user factor vector (if generating recommended movies for a user)
    or movie factor vector (if generating similar movies for a given movie)
    """
    return {
        "query": {
            "function_score": {
                "query": {
                    "query_string": {
                        "query": q
                    }
                },
                "script_score": {
                    "script": {
                        "inline": "payload_vector_score",
                        "lang": "native",
                        "params": {
                            "field": "@model.factor",
                            "vector": query_vec,
                            "cosine": cosine
                        }
                    }
                },
                "boost_mode": "replace"
            }
        }
    }