Note - Double Click to Copy Code Contact Us!

Article search engine using Python

Tech Doubility
Article search engine using Python



  1. from whoosh import index
  2. from whoosh.fields import Schema, TEXT, ID
  3. from whoosh.qparser import QueryParser
  4.  
  5. def create_index():
  6. # Define the schema for the search index
  7. schema = Schema(title=TEXT(stored=True), content=TEXT(stored=True), path=ID(stored=True))
  8.  
  9. # Create a new index in a directory
  10. ix = index.create_in("index_directory", schema)
  11.  
  12. # Open a writer to add documents to the index
  13. writer = ix.writer()
  14.  
  15. # Add sample documents to the index
  16. writer.add_document(title="Document 1", content="This is the content of document 1", path="/doc1")
  17. writer.add_document(title="Document 2", content="This is the content of document 2", path="/doc2")
  18. writer.add_document(title="Document 3", content="This is the content of document 3", path="/doc3")
  19.  
  20. # Commit the changes and close the writer
  21. writer.commit()
  22.  
  23. def search(query):
  24. # Open the index directory
  25. ix = index.open_dir("index_directory")
  26.  
  27. # Create a searcher to perform searches
  28. with ix.searcher() as searcher:
  29. # Create a query parser for the schema
  30. query_parser = QueryParser("content", schema=ix.schema)
  31.  
  32. # Parse the user's query
  33. parsed_query = query_parser.parse(query)
  34.  
  35. # Execute the search and get the results
  36. results = searcher.search(parsed_query)
  37.  
  38. # Print the search results
  39. for hit in results:
  40. print("Title:", hit["title"])
  41. print("Content:", hit["content"])
  42. print("Path:", hit["path"])
  43. print()
  44.  
  45. # Create the search index
  46. create_index()
  47.  
  48. # Perform a search
  49. search("content")

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.