]> BookStack Code Mirror - bookstack/commitdiff
Added search name weighting. Closes #27.
authorDan Brown <redacted>
Sat, 5 Dec 2015 15:11:48 +0000 (15:11 +0000)
committerDan Brown <redacted>
Sat, 5 Dec 2015 15:11:48 +0000 (15:11 +0000)
app/Entity.php
database/migrations/2015_12_05_145049_fulltext_weighting.php [new file with mode: 0644]

index db244e01453b9fd7f6f85cfc6e73d952c3671d20..26878042e5bbca8c51edad3d18236ac00eb6b953 100644 (file)
@@ -134,20 +134,20 @@ abstract class Entity extends Model
             $termString .= $term . '* ';
         }
         $fields = implode(',', $fieldsToSearch);
-        $search = static::whereRaw('MATCH(' . $fields . ') AGAINST(? IN BOOLEAN MODE)', [$termString]);
+        $termStringEscaped = \DB::connection()->getPdo()->quote($termString);
+        $search = static::addSelect(\DB::raw('*, MATCH(name) AGAINST('.$termStringEscaped.' IN BOOLEAN MODE) AS title_relevance'));
+        $search = $search->whereRaw('MATCH(' . $fields . ') AGAINST(? IN BOOLEAN MODE)', [$termString]);
+
+        // Add additional where terms
         foreach ($wheres as $whereTerm) {
             $search->where($whereTerm[0], $whereTerm[1], $whereTerm[2]);
         }
 
-        if (!static::isA('book')) {
-            $search = $search->with('book');
-        }
-
-        if (static::isA('page')) {
-            $search = $search->with('chapter');
-        }
+        // Load in relations
+        if (!static::isA('book')) $search = $search->with('book');
+        if (static::isA('page'))  $search = $search->with('chapter');
 
-        return $search->get();
+        return $search->orderBy('title_relevance', 'desc')->get();
     }
 
     /**
diff --git a/database/migrations/2015_12_05_145049_fulltext_weighting.php b/database/migrations/2015_12_05_145049_fulltext_weighting.php
new file mode 100644 (file)
index 0000000..cef43f6
--- /dev/null
@@ -0,0 +1,37 @@
+<?php
+
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Database\Migrations\Migration;
+
+class FulltextWeighting extends Migration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        DB::statement('ALTER TABLE pages ADD FULLTEXT name_search(name)');
+        DB::statement('ALTER TABLE books ADD FULLTEXT name_search(name)');
+        DB::statement('ALTER TABLE chapters ADD FULLTEXT name_search(name)');
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('pages', function(Blueprint $table) {
+            $table->dropIndex('name_search');
+        });
+        Schema::table('books', function(Blueprint $table) {
+            $table->dropIndex('name_search');
+        });
+        Schema::table('chapters', function(Blueprint $table) {
+            $table->dropIndex('name_search');
+        });
+    }
+}