Solved

adding functionality to perlfect search

Posted on 2000-03-05
8
217 Views
Last Modified: 2010-03-05
This little subroutine splits up the terms the user enters for my perlfect search engine and creates a query....  I already commented out a couple lines because I wanted to make sure there was a match for EVERY term the user entered and no partial matches.. now I want to add some logic so if the user enters something in quotes like... "this is a test", it will search for that exact string in that order, but if there is no quotes it will just search for all of the words (this, is, a, test)...  I am not exaclty sure how this subroutine works, but it looks like it splits the terms looking for spaces....

so basically I need some help to modify this subroutine to look for quotes, and if there are quotes around the terms, I need it to consider it a phrase and search for that phrase.....

here is the routine.. I can post the entire script if I need to:

sub create_query {
  my $query_str = $query->param('q');
  my @terms = split " ", $query_str;
  my $buffer;
  my ($sterm, $nterm);
 
  foreach my $term (@terms) {
    $buffer = normalize($term);
    foreach my $nterm (split " ",$buffer) {
      $sterm = stem($nterm);
#      if ($term =~ /^\+/) {
      if ($terms_db{$sterm}) {
        push @force, $terms_db{$sterm};
#      } else {
#        return 0;
#      }
#     } elsif ($term =~ /^\-/) {
#      push @not, $terms_db{$sterm} if $terms_db{$sterm};
      } else {
      push @other, $terms_db{$sterm} if $terms_db{$sterm};
      }
    }
  }

  return 1;
}
0
Comment
Question by:georgia
8 Comments
 
LVL 16

Expert Comment

by:maneshr
ID: 2585373
sub create_query {
  my $query_str = $query->param('q');

  if ($query_str=~ /^\s+"/ || $query_str=~ /^"){ ## Looks like a phrase, lets check further
   $query_str=~ /\s+"/"/; ## Remove leading & ..
   $query_str=~ /"\s+$/"/; ## .. trailing spaces

   if ($query_str=~ /".*"/){ ## it is a phrase
  push(@terms, $query_str);
  }else{
    @terms = split " ", $query_str;
  }
  }else{
  @terms = split " ", $query_str;
  }

  my $buffer;
  my ($sterm, $nterm);
.....

I dont know that your normalize subroutine does, so i can only provide you with this snippet.

0
 
LVL 3

Expert Comment

by:RobWMartin
ID: 2585421
Not knowing the surrounding code, it is difficult to say.  The specific approach would be to set apart your phrase(s) (i.e. the quoted words) and handle them in an entirely different code segment.  However, you could generalize by setting apart the phrases, then translating each of the words in the phrase to + words, then doing a brute for search for the phrase(s) on the results of the keyword search.  Of course, any of the words in the phrase don't show up in %terms_db, create_query returns failure.

If the search is based on pre-indexing of the source, then it will be more involved.  If the full source (i.e. the information being searched) is available to the program, it may be easier.

There are really too many what-ifs right now.  We do need to see the rest of the code.

However, in all cases the first thing will be to isolate the phrases:

sub create_query {
  my $query_str = $query->param('q');

  my @phrases = $query_str=~/"(.+?)"/g;
  $query_str=~s/"(.+?"//g;
 
  my @terms = split " ", $query_str;
 

Later, we can figure out how to use @phrases to advantage.

Looking forward to seeing the rest of the code.
0
 

Author Comment

by:georgia
ID: 2585447
Here is the entire script:

#!/usr/bin/perl
#$rcs = ' $Id: search.pl,v 1.12 2000/02/06 13:31:36 perlfect Exp $ ' ;

use locale;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use Fcntl;
use Perlfect::Template;

package AnyDBM_File;
@ISA = qw(DB_File GDBM_File SDBM_File ODBM_File NDBM_File) unless @ISA;

for (@ISA) {
  last if eval "require $_";
}

package main;
require './conf.pl';

my %inv_index_db;
my %docs_db;
my %desc_db;
my %titles_db;
my %terms_db;

tie %inv_index_db, AnyDBM_File, $INV_INDEX_DB_FILE, O_RDONLY, 0755 or die "Cannot open $INV_INDEX_DB_FILE: $!";  
tie %docs_db,      AnyDBM_File, $DOCS_DB_FILE, O_RDONLY, 0755      or die "Cannot open $DOCS_DB_FILE: $!";  
tie %desc_db,      AnyDBM_File, $DESC_DB_FILE, O_RDONLY, 0755      or die "Cannot open $DESC_DB_FILE: $!";  
tie %titles_db,    AnyDBM_File, $TITLES_DB_FILE, O_RDONLY, 0755    or die "Cannot open $TITLES_DB_FILE: $!";  
tie %terms_db,     AnyDBM_File, $TERMS_DB_FILE, O_RDONLY, 0755     or die "Cannot open $TERMS_DB_FILE: $!";  

my (@force, @not, @other);
my (@docs, @valid_docs);
my %answer;

my $query = new CGI;

if (create_query()) { #if some valid documents exist
  apply_booleans();
  answer_query();
}  

my $html = cast_template();
print $query->header;
print $html;

sub answer_query {
  my @term_ids = (@force, @other);

  foreach my $term_id (@term_ids) {
    my %v = unpack('f*', $inv_index_db{$term_id});
    foreach my $doc_id (keys %v) {
      $answer{$doc_id} += $v{$doc_id} if grep {/^$doc_id$/} @valid_docs;
    }
  }
}

sub apply_booleans {
  #locate the valid documents by applying the booleans
  my ($term_id, $doc_id, $first_doc_id);
  my %v;
  my (@ary, @not_docs);

  foreach $term_id (@not) {
    %v = unpack("f*", $inv_index_db{$term_id});
    foreach $doc_id (keys %v) {
      push @not_docs, $doc_id unless grep {/^$doc_id$/} @not_docs;
    }
  }
 
  if (@force) {
    $first_doc_id = pop @force;
    %v  = unpack("f*", $inv_index_db{$first_doc_id});
    @valid_docs = keys %v;
    foreach $term_id (@force) {
      %v = unpack("f*", $inv_index_db{$term_id});
      @ary = keys %v;
      @valid_docs = intersection(\@valid_docs, \@ary);
    }
    push @force, $first_doc_id;
  } else {
    @valid_docs = keys %docs_db;
  }

  @valid_docs = minus(\@valid_docs, \@not_docs);
}

sub create_query {
  my $query_str = $query->param('q');
  my @terms = split " ", $query_str;
  my $buffer;
  my ($sterm, $nterm);
 
  foreach my $term (@terms) {
    $buffer = normalize($term);
    foreach my $nterm (split " ",$buffer) {
      $sterm = stem($nterm);
#      if ($term =~ /^\+/) {
      if ($terms_db{$sterm}) {
        push @force, $terms_db{$sterm};
#      } else {
#        return 0;
#      }
#     } elsif ($term =~ /^\-/) {
#      push @not, $terms_db{$sterm} if $terms_db{$sterm};
      } else {
      push @other, $terms_db{$sterm} if $terms_db{$sterm};
      }
    }
  }

  return 1;
}

sub cast_template {
  my %h;
  my $template = new Perlfect::Template($SEARCH_TEMPLATE);
  my $rank = 0;

  $h{script_name} = "Perlfect Search $VERSION";
  $h{query_str}   = $query->param('q');
  $h{results_num} = keys %answer;
 
  my $current_page = $query->param('p');
  $current_page ||= 1;

  my $first = ($current_page - 1) * $RESULTS_PER_PAGE;
  my $last  = $first + $RESULTS_PER_PAGE - 1;
 
  my $real_last = keys %answer;
  if ($last >= $real_last) {
    $last = $real_last - 1;
  }
 
  foreach ((sort {$answer{$b} <=> $answer{$a}} keys %answer)[$first..$last]) {
    my $score = sprintf "%.2f", $answer{$_};
    $template->cast_loop ("results", [{rank => $first+(++$rank),
                               url => $BASE_URL.$docs_db{$_},
                               title => $titles_db{$_},
                               score => $score,
                               description => $desc_db{$_},
                              }]);
  }
  $template->finalize("results");
 
  my $last_page = ceil($real_last, $RESULTS_PER_PAGE);
  $last_page ||= 1;
  my $query_str = CGI::escape($query->param('q'));
  if ($current_page == 1) {
    $h{previous} = "";
    if ($last_page > $current_page) {
      $h{next} = "<A href=\"$SEARCH_URL?q=".$query_str."&p=2\"> Next</A>";  
    } else {
      $h{next} = "";
    }
  } elsif ($current_page == $last_page) {
    $h{previous} = "<A href=\"$SEARCH_URL?q=".$query_str."&p=".($last_page-1)."\">Previous </A>";  
    $h{next} = "";
  } else {
    $h{previous} = "<A href=\"$SEARCH_URL?q=".$query_str."&p=".($current_page-1)."\">Previous </A>";  
    $h{next} = "<A href=\"$SEARCH_URL?q=".$query_str."&p=".($current_page+1)."\"> Next</A>";  
  }
 
  for (1..$last_page) {
    if ($_ != $current_page) {
      $h{navbar} .= "<A href=\"$SEARCH_URL?q=".$query_str."&p=$_\">$_</A> ";
    } else {
      $h{navbar} .= "<B>$_</B> ";
    }
  }

  $h{current_page} = $current_page;
  $h{total_pages}  = $last_page;
  $h{search_url}   = $SEARCH_URL;

  $template->cast(\%h);
  return $template->html;
}

sub normalize {
  my $buffer = $_[0];
 
  $buffer =~ s/-//gs;
  $buffer =~ s/\W/ /gs;
  $buffer =~ s/\b\d+\b/ /gs;
  $buffer =~ s/[\n\s]+/ /gs;
  $buffer =~ s/^\s+//gs;
  $buffer =~ s/\s+$//gs;
  $buffer = lc $buffer;

  return $buffer;
}

sub stem {
  my $str = $_[0];
  $str = substr $str, 0, $STEMCHARS if $STEMCHARS;
  return $str;
}

sub ceil {
  my $x = $_[0];
  my $y = $_[1];

  if ($x % $y == 0) {
    return $x / $y;
  } else {
    return int($x / $y + 1);
  }
}

sub intersection {
  my ($ra, $rb) = @_;
  my @i;
 
  foreach my $doc_id (@{$ra}) {
    push @i, $doc_id if grep {/^$doc_id$/} @{$rb};
  }

  return @i;
}

sub minus {
  my ($ra, $rb) = @_;
  my @i;

  foreach my $doc_id (@{$ra}) {
    push @i, $doc_id unless grep {/^$doc_id$/} @{$rb};
  }
 
  return @i;
}
0
 
LVL 84

Expert Comment

by:ozo
ID: 2585457
use Text::ParseWords;
@terms=quotewords('\s+', 0,  $query_str);
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 

Author Comment

by:georgia
ID: 2585486
That sounds easy enough ozo... where exactly do I put those lines... I am kind of new.
0
 

Author Comment

by:georgia
ID: 2588530
maneshr,

Will your snippet work with the script I pasted?
0
 
LVL 3

Accepted Solution

by:
RobWMartin earned 200 total points
ID: 2588767
This doesn't look like a simple query_str parsing problem.  I think the problem you are going to run into, is how the search sources are indexed.  If you simply extract phrases from the search string and call them terms, are those phrases indexed in terms_db ( or inv_index_db )?  If they are not, then you will not get what you are looking for.  You will need to break up the phrase into +'ed terms, then search the results (the source documents) for the exact phrases using some straight string search.  Also, you will have to mod the terms_db lookup on forced terms to keep from immediately failing if the phrase has junk words (like "the") in it.  May require another database (of junk words) so you can say "force the terms of this phrase, but only if they are not junk."  It isn't going to be a simple solution.

Unfortunately, I don't have time to pursue this;  those who sign my paycheck, have other ideas about what I should be doing right now:)  Sorry, but I did want to give my 2 cents on where I see difficulty lurking.

You've got two of the best (i.e. ozo and maneshr) still on it, though (hopefully).

G'luck
0
 

Author Comment

by:georgia
ID: 2601730
Thank you... I was afraid of that.  You are right the index will not work with phrases so being able to set the terms won't help.

Aaron
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

I've just discovered very important differences between Windows an Unix formats in Perl,at least 5.xx.. MOST IMPORTANT: Use Unix file format while saving Your script. otherwise it will have ^M s or smth likely weird in the EOL, Then DO NOT use m…
On Microsoft Windows, if  when you click or type the name of a .pl file, you get an error "is not recognized as an internal or external command, operable program or batch file", then this means you do not have the .pl file extension associated with …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now