elasticsearch查询should和must

elasticsearch在should和must查询时不能精确查出数据,主要原因是在7.0版本后should查询时minimum_should_match默认为0,查出了非should条件中的数据。

minimum_should_match可以控制查询精度,在should和must联合查询查询时必须使用,否则查不出精确的数据。

{
    "size":20,
    "query":{
        "bool":{
            "should":[
                {
                    "match_phrase":{
                        "Title":"关键词"
                    }
                },
                {
                    "match_phrase":{
                        "summary":"关键词"
                    }
                },
                {
                    "match_phrase":{
                        "Content":"关键词"
                    }
                }
            ],
            "minimum_should_match":1,
            "must":{
                "match_phrase":{
                    "categoryId":0
                }
            }
        }
    }
}

minimum_should_match为1时,表示无管should有多少可选条件子句,至少满足1个条件。

minimum_should_match为-1时,负数时,至少满足should可选子句的总数减去此数字应该是必需的。

 

如果不使用minimum_should_match,还有一种解决方案。

(categoryId=0&Title="关键词")||(categoryId=0&summary="关键词")||(categoryId=0&Content="关键词")

{
    "size":20,
    "query":{
        "bool":{
            "should":[
                {
                    "bool":{
                        "must":[
                            {
                                "match_phrase":{
                                    "categoryId":0
                                }
                            },
                            {
                                "match_phrase":{
                                    "Title":"关键词"
                                }
                            }
                        ]
                    }
                },
                {
                    "bool":{
                        "must":[
                            {
                                "match_phrase":{
                                    "categoryId":0
                                }
                            },
                            {
                                "match_phrase":{
                                    "summary":"关键词"
                                }
                            }
                        ]
                    }
                },
                {
                    "bool":{
                        "must":[
                            {
                                "match_phrase":{
                                    "categoryId":0
                                }
                            },
                            {
                                "match_phrase":{
                                    "Content":"关键词"
                                }
                            }
                        ]
                    }
                }
            ]
        }
    }
}

 

posted @ 2021-04-21 14:10  yuejin  阅读(2499)  评论(0编辑  收藏  举报