sql >> Databasteknik >  >> NoSQL >> MongoDB

Hur man gör fulltextsökning i MongoDB

En av de ledande NoSQL-databaserna, MongoDB är välkänd för sin snabba prestanda, mångsidiga schema, skalbarhet och fantastiska möjligheter för indexering. Låt oss titta på lite sammanhang innan vi går in på några detaljer. Fulltextsökning är en viktig funktion när vi pratar om att hitta innehåll på internet. En google-sökning är det bästa exemplet på detta när vi ser innehållet med hjälp av fraser eller nyckelord. I den här artikeln kommer vi att lära oss om fulltextsökningsmöjligheter i MongoDB baserat på textindex.

Skapa en exempeldatabas

Innan vi börjar kommer vi att skapa en exempeldatabas som kommer att användas under handledningen.

Vi kommer att skapa en databas med namnet myDB och skapa en samling med namnet böcker . För detta skulle uttalandet vara följande.

> use myDB
> db.createCollection("books")
>

Låt oss infoga några dokument genom att använda följande uttalande.

> db.books.insert([
	{
      "title": "Eloquent JavaScript, Second Edition",
      "subtitle": "A Modern Introduction to Programming",
      "author": "Marijn Haverbeke",
      "publisher": "No Starch Press",
      "description": "JavaScript lies at the heart of almost every modern web application, from social apps to the newest browser-based games. Though simple for beginners to pick up and play with, JavaScript is a flexible, complex language that you can use to build full-scale applications."
    },
    {
      "title": "Learning JavaScript Design Patterns",
      "subtitle": "A JavaScript and jQuery Developer's Guide",
      "author": "Addy Osmani",
      "publisher": "O'Reilly Media",
      "description": "With Learning JavaScript Design Patterns, you'll learn how to write beautiful, structured, and maintainable JavaScript by applying classical and modern design patterns to the language. If you want to keep your code efficient, more manageable, and up-to-date with the latest best practices, this book is for you."
    },
    {
      "title": "Speaking JavaScript",
      "subtitle": "An In-Depth Guide for Programmers",
      "author": "Axel Rauschmayer",
      "publisher": "O'Reilly Media",
      "description": "Like it or not, JavaScript is everywhere these days, from browser to server to mobile and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position."
    },
    {
      "title": "Programming JavaScript Applications",
      "subtitle": "Robust Web Architecture with Node, HTML5, and Modern JS Libraries",
      "author": "Eric Elliott",
      "publisher": "O'Reilly Media",
      "description": "Take advantage of JavaScript's power to build robust web-scale or enterprise applications that are easy to extend and maintain. By applying the design patterns outlined in this practical book, experienced JavaScript developers will learn how to write flexible and resilient code that's easier-yes, easier-to work with as your codebase grows."
    },
    {
      "title": "Understanding ECMAScript 6",
      "subtitle": "The Definitive Guide for JavaScript Developers",
      "author": "Nicholas C. Zakas",
      "publisher": "No Starch Press",
      "description": "ECMAScript 6 represents the biggest update to the core of JavaScript in the history of the language. In Understanding ECMAScript 6, expert developer Nicholas C. Zakas provides a complete guide to the object types, syntax, and other exciting changes that ECMAScript 6 brings to JavaScript."
    }
])

Skapa ett textindex

Vi måste skapa ett textindex på fälten för att utföra textsökningen. Vi kan skapa detta på enstaka eller flera fält. Följande sats kommer att skapa ett textindex på ett enda fält.

>db.books.createIndex({"description":"text"})

Vi kommer att skapa ett textindex på beskrivningen och undertext fält för denna handledning. Vi kan bara skapa ett textindex per samling i MongoDB. Så vi kommer att skapa ett sammansatt textindex med hjälp av följande påstående.

>db.books.createIndex({"subtitle":"text","description":"text"})

Nu ska vi försöka söka efter dokument som har nyckelorden 'ECMAScript' i beskrivningen och undertext fält. För detta kan vi använda uttalandet nedan.

db.books.find({$text: {$search: "ECMAScript"}})

Exempel

>db.books.find({$text: {$search: "ECMAScript"}},{ subtitle: 1, description: 1 })
	{
    "_id" : ObjectId("602b09cb3cb6144ada1c62fe"),
    "subtitle" : "The Definitive Guide for JavaScript Developers",
    "description" : "ECMAScript 6 represents the biggest update to the core of JavaScript in the history of the language. In Understanding ECMAScript 6, expert developer Nicholas C. Zakas provides a complete guide to the object types, syntax, and other exciting changes that ECMAScript 6 brings to JavaScript."
	}
>

Fraser

Du kan söka efter fraser med hjälp av textindex. Som standard utför textsökning en ELLER-sökning efter alla ord i frasen. Om du vill söka efter "moderna designmönster" kommer den att söka efter dokument med nyckelorden antingen modern, design eller patterns.

Exempel

>db.books.find({$text: {$search: "modern design patterns"}},{ subtitle: 1, description: 1 })
	{
    "_id" : ObjectId("602b098f3cb6144ada1c2ea1"),
    "subtitle" : "A JavaScript and jQuery Developer's Guide",
    "description" : "With Learning JavaScript Design Patterns, you'll learn how to write beautiful, structured, and maintainable JavaScript by applying classical and modern design patterns to the language. If you want to keep your code efficient, more manageable, and up-to-date with the latest best practices, this book is for you."
	},
	{
    "_id" : ObjectId("602b09b93cb6144ada1c4bca"),
    "subtitle" : "Robust Web Architecture with Node, HTML5, and Modern JS Libraries",
    "description" : "Take advantage of JavaScript's power to build robust web-scale or enterprise applications that are easy to extend and maintain. By applying the design patterns outlined in this practical book, experienced JavaScript developers will learn how to write flexible and resilient code that's easier-yes, easier-to work with as your code base grows.",
	},
	{
    "_id" : ObjectId("602b095c3cb6144ada1c1028"),
    "subtitle" : "A Modern Introduction to Programming",
    "description" : "JavaScript lies at the heart of almost every modern web application, from social apps to the newest browser-based games. Though simple for beginners to pick up and play with, JavaScript is a flexible, complex language that you can use to build full-scale applications."
	}
>

Om du vill söka efter exakta fraser som dokument med "moderna designmönster" tillsammans kan du göra det genom att ange dubbla citattecken i söktexten.

Exempel

>db.books.find({$text: {$search: "\"modern design patterns\""}},{ subtitle: 1, description: 1 })
	{
    "_id" : ObjectId("602b098f3cb6144ada1c2ea1"),
    "subtitle" : "A JavaScript and jQuery Developer's Guide",
    "description" : "With Learning JavaScript Design Patterns, you'll learn how to write beautiful, structured, and maintainable JavaScript by applying classical and modern design patterns to the language. If you want to keep your code efficient, more manageable, and up-to-date with the latest best practices, this book is for you."
}

Negationer

Om du vill utesluta dokument som innehåller ett visst ord kan du använda en negationssökning. Om du till exempel ska söka i alla dokument med "JavaScript" men inte "HTML5" eller "ECMAScript", kan du söka som exemplet nedan.

Exempel

>db.books.find({$text: {$search: "JavaScript -HTML5 -ECMAScript"}},{ subtitle: 1, description: 1 })
	{
    "_id" : ObjectId("602b098f3cb6144ada1c2ea1"),
    "subtitle" : "A JavaScript and jQuery Developer's Guide",
    "description" : "With Learning JavaScript Design Patterns, you'll learn how to write beautiful, structured, and maintainable JavaScript by applying classical and modern design patterns to the language. If you want to keep your code efficient, more manageable, and up-to-date with the latest best practices, this book is for you."
	},
	{
    "_id" : ObjectId("602b09a83cb6144ada1c4973"),
    "subtitle" : "An In-Depth Guide for Programmers",
    "description" : "Like it or not, JavaScript is everywhere these days, from browser to server to mobile and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position."
	},
	{
    "_id" : ObjectId("602b095c3cb6144ada1c1028"),
    "subtitle" : "A Modern Introduction to Programming",
    "description" : "JavaScript lies at the heart of almost every modern web application, from social apps to the newest browser-based games. Though simple for beginners to pick up and play with, JavaScript is a flexible, complex language that you can use to build full-scale applications."
	}

Textsökningsresultat

Textsökningen ger varje dokument en poäng som representerar dokumentets relevans med sökfrågan. Denna poäng kan användas för att sortera alla poster som returneras i sökresultatet. En högre poäng kommer att indikera en mest relevant match.

Exempel

>db.books.find({$text: {$search: "JavaScript "}},{score: {$meta: "textScore"}, subtitle: 1, description: 1 }).sort({score:{$meta:"textScore"}})
	{
    "_id" : ObjectId("602b098f3cb6144ada1c2ea1"),
    "subtitle" : "A JavaScript and jQuery Developer's Guide",
    "description" : "With Learning JavaScript Design Patterns, you'll learn how to write beautiful, structured, and maintainable JavaScript by applying classical and modern design patterns to the language. If you want to keep your code efficient, more manageable, and up-to-date with the latest best practices, this book is for you.",
    "score" : 1.43269230769231
	},
	{
    "_id" : ObjectId("602b09cb3cb6144ada1c62fe"),
    "subtitle" : "The Definitive Guide for JavaScript Developers",
    "description" : "ECMAScript 6 represents the biggest update to the core of JavaScript in the history of the language. In Understanding ECMAScript 6, expert developer Nicholas C. Zakas provides a complete guide to the object types, syntax, and other exciting changes that ECMAScript 6 brings to JavaScript.",
    "score" : 1.42672413793103
	},
	{
    "_id" : ObjectId("602b09a83cb6144ada1c4973"),
    "subtitle" : "An In-Depth Guide for Programmers",
    "description" : "Like it or not, JavaScript is everywhere these days, from browser to server to mobile and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position.",
    "score" : 0.818181818181818
	},
	{
    "_id" : ObjectId("602b095c3cb6144ada1c1028"),
    "subtitle" : "A Modern Introduction to Programming",
    "description" : "JavaScript lies at the heart of almost every modern web application, from social apps to the newest browser-based games. Though simple for beginners to pick up and play with, JavaScript is a flexible, complex language that you can use to build full-scale applications.",
    "score" : 0.801724137931034
	},
	{
    "_id" : ObjectId("602b09b93cb6144ada1c4bca"),
    "subtitle" : "Robust Web Architecture with Node, HTML5, and Modern JS Libraries",
    "description" : "Take advantage of JavaScript's power to build robust web-scale or enterprise applications that are easy to extend and maintain. By applying the design patterns outlined in this practical book, experienced JavaScript developers will learn how to write flexible and resilient code that's easier-yes, easier-to work with as your codebase grows.",
    "score" : 0.792857142857143
	}

Stoppord

Operatorn $text filtrerar bort de språkspecifika stopporden, såsom a, an, the och på engelska. Sökningen nedan kommer inte att returnera något dokument i resultatet.

Exempel

>db.books.find({$text: {$search: "is"}},{subtitle: 1, description: 1 })
	Fetched 0 record(s)

Stammord

Operatorn $text matchar hela ordet med stamstammar. Så om något dokumentfält innehåller ordet lära sig eller lära sig, skulle en sökning på termen lära sig eller lära resultera i detsamma.

Exempel

>db.books.find({$text: {$search: " learn"}},{subtitle: 1, description: 1 }) or >db.books.find({$text: {$search: " learning"}},{subtitle: 1, description: 1 })
	{
    "_id" : ObjectId("602b098f3cb6144ada1c2ea1"),
    "subtitle" : "A JavaScript and jQuery Developer's Guide",
    "description" : "With Learning JavaScript Design Patterns, you'll learn how to write beautiful, structured, and maintainable JavaScript by applying classical and modern design patterns to the language. If you want to keep your code efficient, more manageable, and up-to-date with the latest best practices, this book is for you."
	},
	{
    "_id" : ObjectId("602b09a83cb6144ada1c4973"),
    "subtitle" : "An In-Depth Guide for Programmers",
    "description" : "Like it or not, JavaScript is everywhere these days, from browser to server to mobile and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position."
	},
	{
    "_id" : ObjectId("602b09b93cb6144ada1c4bca"),
    "subtitle" : "Robust Web Architecture with Node, HTML5, and Modern JS Libraries",
    "description" : "Take advantage of JavaScript's power to build robust web-scale or enterprise applications that are easy to extend and maintain. By applying the design patterns outlined in this practical book, experienced JavaScript developers will learn how to write flexible and resilient code that's easier-yes, easier-to work with as your codebase grows."
	}

Slutsats

Jag hoppas att du lärde dig något nytt idag. Här är en intressant artikel om Self-Hosted MongoDB. Jag inbjuder dig också att prova saker på egen hand och dela dina erfarenheter i kommentarsfältet. Dessutom, om du stöter på några problem med någon av definitionerna ovan får du gärna fråga mig i kommentarsfältet nedan.


  1. Snabbt sätt att hitta dubbletter på indexerad kolumn i mongodb

  2. Hur skapar man en egen databas i Redis?

  3. Snabbreferensguide till olika NoSQL-databaser

  4. Ersätter inbäddat dokument i array i MongoDB