MongoDB Text Search AND multiple search words

后端 未结 4 1113
梦毁少年i
梦毁少年i 2020-11-29 01:13

I have an index on an array \"keys\" that I am using to provide full text functionality to my applicaiton.

With the release of 2.4.3, I\'d like to utilize the \"text

相关标签:
4条回答
  • 2020-11-29 01:52

    As @alecxe pointed out earlier, to do AND search on text index column you need to double quote each search word. Below is a quick one-liner for your requirement.

    db.supplies.runCommand("text", {search: "printer ink".split(" ").map(str => "\""+str+"\"").join(' ')})
    
    0 讨论(0)
  • 2020-11-29 01:58

    You can wrap each word in double-quotes:

    let keywords = ctx.params.query.split(/\s+/).map(kw => `"${kw}"`).join(' ');
    match.$text = { $search: keywords, $caseSensitive: false };
    

    There is a downside if the user inputs a quoted string this will not work. You'd have to parse out quoted strings first.

    0 讨论(0)
  • 2020-11-29 02:01

    Here is a simple function I made to search using subwords in node. Hope it helps someone

    Let's suppose a user search for pri nks so it should satisfy printer and inks but $text search doesn't allow for this so here is my simple function:

        var makeTextFilter = (text) => {
        var wordSplited = text.split(/\s+/);
        /** Regex generation for words */
        var regToMatch = new RegExp(wordSplited.join("|"), 'gi');
        let filter = [];
        searchFieldArray.map((item,i) => {
            filter.push({}); 
            filter[i][item] = {
                $regex: regToMatch,
                $options: 'i'
            }
        })
    
        return filter;
      }
    

    and use it in your query like this

    let query = {...query, $or: makeTextFilter(textInputFromUser)}
    tableName.find(query, function (err, cargo_list)
    
    0 讨论(0)
  • 2020-11-29 02:06

    Give a try to:

    db.supplies.runCommand("text", {search:"\"printer\" \"ink\""})
    

    Also, here's a quote from docs:

    If the search string includes phrases, the search performs an AND with any other terms in the search string; e.g. search for "\"twinkle twinkle\" little star" searches for "twinkle twinkle" and ("little" or "star").

    Hope that helps.

    0 讨论(0)
提交回复
热议问题